import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import Skeleton from 'taro-skeleton'
import {connect} from 'react-redux';
import {
  Block,
  Button,
  Checkbox,
  Icon,
  Image,
  Input,
  Navigator,
  Picker,
  ScrollView,
  Text,
  View
} from '@tarojs/components';
import {
  AtCalendar,
  AtFloatLayout,
  AtForm,
  AtIcon,
  AtInput,
  AtInputNumber,
  AtList,
  AtListItem,
  AtModal,
  AtModalContent,
  AtSwitch
} from 'taro-ui';
import {
  CalendarInfo,
  DefaultInfo,
  GetFeeDataType,
  OrderGoodDetail,
  OrderGoodItem,
  PlatformSet,
  redbagItem,
  ServerData
} from '../../utils/server.interface';
import {user} from '../../utils/user.service';
import {http} from '../../utils/http';
import {
  BASE_URL,
  CALENDAR_INFO,
  CHECK_GROUP_STATUS,
  CREATE_AND_PAY,
  DEL_LINK_INFO,
  FACE,
  GET_DEFAULT_INFO,
  GET_FEE,
  GET_LINK_INFO,
  GET_LINK_INFO_LIST,
  GET_PHONE,
  H5_ORDER_PAY,
  materialMedia,
  NEW_COUPON_PAY,
  NEW_PAY_CREATE_ORDER,
  NEW_PAY_PARAMS,
  NEW_ZERO_PAY,
  OCR,
  ORDER_GOOD_DETAIL,
  PC_ORDER_STATUS,
  PC_QRCODE,
  REGION_ALL,
  RESOURCE_URL,
  TARO_ENV,
  TRANS_ORDER_DETAIL,
  UPLODE_FALE,
  FETCH_SECKILL_CREATE
} from '../../constants/api';
import {DateType} from '../../reducers/select-date';
import {payment} from '../../utils/payment.service';
import Calendar from '../components/calendar/calendar';
import {getTempSellerId, toIosDateFormat, clearSearch} from '../../utils/tools'
import {platform} from '../../utils/platform-settting.service';
import {newHttp} from '../../utils/request';
import NumberInput from "../components/number-input/number-input";
import {h5Wx} from "../../utils/h5.service";
import {getGlobalData} from "../../utils/global"
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {lxH5Wx} from "../../utils/lx.h5.service";
import {getContent} from "../../utils/handlerPublicCode";
import './confirm.scss';

interface StateType {
  isDaypartingAppointment: boolean
  defaultDate: boolean
  ticketSubMiting: boolean
  linkShow: boolean
  openKD: boolean
  openTraveler: boolean // 出行人下单
  force_platform_seller: any
  bottomView: any
  limitGoodsId: any
  goodsDiscountCodeType: any
  goodsDiscountCodeId: any
  regions: any
  detailShow: any
  activityId: any
  goodUuid: any
  addressData: any
  rangeKey: any
  rangeData: any
  fromGoodDetail: any
  paySuccessShow: boolean
  showLoading: boolean
  agree: boolean
  showLoadingLink: boolean
  delIndex: number
  editId: string
  fieldCustomError: any
  fieldCustom: any
  oldNum: number
  custom_item_config: any
  region: any
  linkDataList: any
  indextime: number
  days: number
  itemH: number
  mealsValidDate: string
  notice: string
  floatLayout: boolean
  week: any
  lookMoreShow: boolean
  threeDate: any
  floatLayoutIdcard: boolean
  layoutIndex: number
  idcardDelIndex: string
  payData: {
    province: string
    city: string
    region: string
    address: string
    comments: string
    idcard: string
    mark: string
    name: string
    phone: string
    upload_file: []
    face: string
  }
  contactData: any
  disable: boolean
  alldisable: boolean
  useIntegral: boolean
  redbag: redbagItem | false
  goodDetail: OrderGoodDetail | false
  isiPhonex: boolean
  upFee: boolean
  getFee: {
    consume_fee: number
    num: number
    maxJf?: number
    proJf?: number
    goodsId: number
    goodsPrice: number
    buyDate: string
    hongbaoId: number
    jf: number
    useIntegral: boolean
    buy_num_min?: number
    buy_num_max?: number
    can_use_coupon: number
    coupon_list: any
    couponIsuseId?: number | string
  }
  opentips: boolean
  feeInfo: GetFeeDataType
  redbagId: number
  step: number
  userForm: UserForm[]
  userFormTemplate: string
  agreement: boolean
  showCalendar: boolean
  calendarInfo: CalendarInfo[]
  goodsGroup: { good_id: number; num: number; name: string; buy_num_min: number; buy_num_max: number; tips_msg?: any; opentips?: boolean }[]
  buyDate: { start: string; end: string }
  submiting: boolean
  newPayOrderId: string
  platformSet: PlatformSet | false
  isSaveLinkInfo: boolean
  lineList: LineList[]
  checkId: number
  userBalance: boolean
  canBalance?: boolean
  recharge: boolean
  custom_item_key: string
  assembling_place: string
  zero: 0 | 1
  isLeader: any
  onlyTicketPay: any
  fristShow: boolean
  booking_day_end: number
  booking_time_end: string
  upCount: number
  mealArrId: string
  look: boolean
  payEnd: boolean
  welfare: boolean
  flAry: any
  flAryIndex: number
  flAryMsg: string
  userOk: number
  thisBuyDate: string
  meals?: {
    productName: string
    amount: number
    id: number
  }[]
  couponMoney: number
  offOpenCoupon: boolean
  notUse: boolean
  tempSellerId: string
  env: string
  newPayOrderIdRet: string
  pcqrcode: ''
}

interface LineList {
  value: string
  id: number
  config?: object
}

interface GetFeeType {
  num: number
  goodsId: number
  buyDate: string
  dateRange: string
  startDate: string
  endDate: string
  hongbaoId: string
  userBalance?: number
  jf: number
  maxJf?: number
  useIntegral: boolean
  goodsGroup?: string
  buy_num_min?: number
  buy_num_max?: number
  mealArrId?: string
  isOpenCredit?: number
  creditAmount?: number
  can?: boolean
}

interface FieldType {
  require: boolean
  value: string
}

interface UserForm {
  comments: FieldType
  name: FieldType
  phone: FieldType
  region: { require: boolean; value: string[] }
  address: FieldType
  idcard: FieldType
  mark: FieldType
  upload_file: { require: boolean; value: string[] }
  custom: {
    title: string
    value: string
    require: boolean
    key: string
  }[]
}

interface FormData {
  hongbao: number
  buy_date?: string
  message?: string
  linkman: string
  phone: string
  identity_num: string
  remark: string
  face: string
  custom_item_detail: string
  custom_item_key?: string
  isSaveLinkInfo?: number
  goods_id: number
  defined_img?: string
  buy_amount: number
  hongbao_id: number
  dateRange?: string // {"start":"2019-11-23","end":"2019-11-24"}
  reciver_province: string
  reciver_city: string
  reciver_area: string
  delivery_address: string
  useIntegral: boolean
  jf: number
  goodsGroup: string
  canBalance?: boolean
  referSellerId?: number
  couponIsuseId?: number | string
  pageType?: string
}

type PageStateProps = {
  selectDate: DateType
}

type PageDispatchProps = {}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Confirm {
  props: IProps
}


@connect(({selectDate}) => ({
  selectDate,
}), (dispatch) => ({}))

class Confirm extends Component {
  state: StateType = {
    isDaypartingAppointment: false, // 是否为免费入园的分时预约
    defaultDate: true, // 默认选中时间，true：默认，false: 不默认
    ticketSubMiting: false,
    linkShow: false,
    bottomView: '',
    openKD: false,
    openKD: true,
    openTraveler: true,
    force_platform_seller: '',
    limitGoodsId: '',
    goodsDiscountCodeType: '',
    goodsDiscountCodeId: '',
    activityId: '',
    detailShow: false,
    goodUuid: '',
    rangeKey: [0, 0, 0],
    regions: [],
    addressData: [],
    rangeData: [[], [], []],
    fromGoodDetail: null,
    showLoading: true,
    agree: false,
    paySuccessShow: false,
    showLoadingLink: true,
    delIndex: 0,
    editId: '',
    fieldCustomError: {
      province: '请选择省市区',
      city: '请选择省市区',
      region: '请选择省市区',
      address: '请输入详细地址',
      comments: '请输入留言',
      idcard: '请输入身份证号码',
      mark: '请输入备注',
      name: '请输入姓名',
      phone: '请输入手机号',
      upload_file: '请上传图片',
      face: '请上传人脸照片'
    },
    fieldCustom: [],
    oldNum: 1,
    custom_item_config: [],
    region: [],
    linkDataList: [],
    indextime: 0,
    days: 1,
    itemH: 0,
    mealsValidDate: '',
    notice: '',
    floatLayout: false,
    week: ['周天', '周一', '周二', '周三', '周四', '周五', '周六'],
    lookMoreShow: false,
    threeDate: [],
    floatLayoutIdcard: false,
    layoutIndex: 0,
    idcardDelIndex: '',
    payData: {
      phone: '',
      name: '',
      province: '',
      city: '',
      region: '',
      address: '',
      comments: '',
      idcard: '',
      mark: '',
      upload_file: [],
      face: ''
    },
    contactData: [],
    disable: false,
    alldisable: false,
    useIntegral: false,
    isiPhonex: false,
    upFee: false,
    redbag: false,
    goodDetail: false,
    custom_item_key: '',
    lineList: [],
    checkId: 0,
    userBalance: false,
    getFee: {
      consume_fee: 0.00,
      num: 0,
      goodsId: 0,
      buyDate: '',
      goodsPrice: 0,
      hongbaoId: 0,
      jf: 0,
      useIntegral: false,
      buy_num_min: 0,
      buy_num_max: 1000,
      couponIsuseId: 0,
    },
    opentips: false,
    feeInfo: {
      hbAmount: 0,
      integralDeduction: 0,
      can: false,
      maxAmount: 0,
      num: 0,
      totalFee: 0,
      userBalance: 0,
      couponIsuseId: 0,
      platform_pay_type: 1
    },
    redbagId: 0,
    step: 1,
    userForm: [],
    agreement: false,
    userFormTemplate: '',
    showCalendar: false,
    calendarInfo: [],
    goodsGroup: [],
    buyDate: {start: '', end: '',},
    submiting: false,
    newPayOrderId: '',
    isSaveLinkInfo: true,
    canBalance: false,
    recharge: false,
    zero: 0,
    isLeader: 0,
    onlyTicketPay: '',
    fristShow: false,
    assembling_place: '',
    booking_day_end: 0,
    booking_time_end: '23:59:00',
    upCount: 1,
    mealArrId: '',
    look: false,
    payEnd: false,
    platformSet: false,
    welfare: false,
    flAry: [''],
    flAryIndex: -1,
    meals: [],
    flAryMsg: '请确认你的兑换码是正确的或未使用过',
    userOk: 1,
    thisBuyDate: '',
    couponMoney: 0,
    couponMoneyName: '',
    offOpenCoupon: false,
    notUse: true,
    tempSellerId: '',
    env: '',
    newPayOrderIdRet: '',
    pcqrcode: '',
    pageType: ''
  }
  goodId = 0
  goodUuid

  calcTomorrow(start) {
    const startTime = new Date(start).getTime()
    const newTime = startTime + (1 * 24 * 60 * 60 * 1000)
    const newTimeDate = new Date(newTime)
    let text = ''
    text += newTimeDate.getFullYear() + '-'
    text += newTimeDate.getMonth() + 1 < 10 ? '0' + (newTimeDate.getMonth() + 1) : newTimeDate.getMonth() + 1
    text += '-'
    text += newTimeDate.getDate() < 10 ? '0' + newTimeDate.getDate() : newTimeDate.getDate()
    return text
  }

  initDate = false

  async initCalendatData(goodDetail = this.state.goodDetail) {
    const calendarInfo = await http.get<CalendarInfo[]>(CALENDAR_INFO, {goodsUuid: goodDetail.goods.uuid})
    const {getFee} = this.state
    if (calendarInfo && calendarInfo.length > 0) {
      const data = await this.ckeckStock(calendarInfo)
      const firstDay = data.date
      if (new Date(toIosDateFormat(firstDay)).getTime() > new Date(toIosDateFormat(this.state.buyDate.start)).getTime() && goodDetail.goods.category !== 2) {
        const good = calendarInfo.find(item => item.date === this.state.buyDate.start)
        const that = this
        if (!good || !good.surplus_stock) {
          this.setState({
            buyDate: {
              start: data.date,
              end: this.calcTomorrow(data.date)
            }
          }, async () => {
            const feeInfo = await that.getFee(false)
            getFee.buy_num_max = feeInfo.buy_num_max
            getFee.buy_num_min = feeInfo.buy_num_min
            getFee.num = feeInfo.num ? feeInfo.num : getFee.num
            that.setState({feeInfo, getFee, fristShow: true}, () => {
              if (goodDetail.goods.category !== 4) {
                that.integralChange(feeInfo.maxJf)
              }
              if (goodDetail.goods.is_open != 0) {
              }
            })
          })
        }
      }
      this.setState({calendarInfo})
    } else {
      Taro.showModal({
        title: '提示',
        content: '当前产品没有可购买日期，点击返回上一页',
        success: function (res) {
          if (res.confirm) {
            Taro.navigateBack()
          }
        },
        showCancel: false
      })
    }
  }

  async ckeckStock(data) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].surplus_stock) {
        return data[i]
        break
      }
    }
  }

  async getLineList(config) {
    const conf = []
    for (const key in config) {
      if (config[key]) {
        if (config[key].k) {
          conf.push(config[key].k)
        } else {
          conf.push(key)
        }
      }
    }
    this.setState({
      custom_item_key: conf.join(',')
    })
    const lineList = await http.get<LineList>(GET_LINK_INFO, {config: conf.join(',')})
    if (lineList) {
      lineList.map(item => {
        item['config'] = JSON.parse(item.value)
      })
      this.setState({
        lineList
      })
    }
  }

  formatUserFormData(good: OrderGoodItem): string {
    if (good && good.is_custom_item >= 0) {
      const config = JSON.parse(good.custom_item_config)
      if (good.is_custom_item === 0) {
        this.getLineList(config)
      }
      const newFormat: { [key: string]: any } = {custom: []}
      if (config) {
        Object.keys(config).map(item => {
          if (item.indexOf('field') >= 0) {
            newFormat['custom'].push({key: item, value: '', title: config[item].k, require: config[item].ckd})
          } else {
            newFormat[item] = {value: item == 'upload_file' ? [] : '', require: config[item]}
          }
        })
      } else {
        return JSON.stringify({
          name: {require: true, value: ''},
          phone: {require: true, value: ''},
          mark: {require: Boolean(good.is_show_mark), value: ''},
          region: {require: Boolean(good.is_require_buyer_address), value: []},
          address: {require: Boolean(good.is_require_buyer_address), value: ''},
          idcard: {require: Boolean(good.is_require_buyer_idcard), value: ''},
          upload_file: {require: Boolean(good.is_require_buyer_upload_file), value: []},
          comments: {require: Boolean(good.is_require_buyer_comments), value: ''},
          custom: []
        })
      }

      newFormat['region'] = {require: newFormat.address, value: []}
      return JSON.stringify(newFormat)  // 解决深拷贝问题
    } else {
      return JSON.stringify({
        name: {require: true, value: ''},
        phone: {require: true, value: ''},
        mark: {require: Boolean(good.is_show_mark), value: ''},
        region: {require: Boolean(good.is_require_buyer_address), value: []},
        address: {require: Boolean(good.is_require_buyer_address), value: ''},
        idcard: {require: Boolean(good.is_require_buyer_idcard), value: ''},
        upload_file: {require: Boolean(good.is_require_buyer_upload_file), value: []},
        custom: []
      })
    }
  }

  getStep(good: OrderGoodItem): number {
    if (good.exchange_type === 1) {
      const tmp = (good.exchange_max_integral / (good.exchange_money * 100))
      if (tmp > 1) {
        return Math.ceil(tmp)
      } else {
        return 1
      }
    } else {
      return 1
    }
  }

  siteHash = ''

  async UNSAFE_componentWillMount() {
    if (TARO_ENV === 'weapp') {
      Taro.hideShareMenu()
      const extConfig = Taro.getExtConfigSync();
      this.siteHash = extConfig['p-key'] || '';
    } else {
      const extConfig = Taro.getStorageSync('user');
      this.siteHash = extConfig.pkey || '';
    }
    if (process.env.TARO_ENV === 'h5') {
      const data = await http.carGet(REGION_ALL)
      this.setState({addressData: data}, async () => {
        this.handleCityData([0, 0, 0]);
      })
    }
    if (Taro.getCurrentInstance().router.params.isDaypartingAppointment) {
      this.setState({isDaypartingAppointment: true});
    } else {
      this.setState({isDaypartingAppointment: false});
    }
    this.setState({env: Taro.getCurrentInstance().router.params.env});
    const platformSet = await platform.getSetting()
    if (platformSet.is_order_default_check_date && platformSet.is_order_default_check_date == 1) {
      this.setState({defaultDate: false})
    } else {
      this.setState({defaultDate: true})
    }
    // if (!platformSet.is_order_default_check_daten || platformSet.is_order_default_check_daten == 1) {
    //   this.setState({defaultDate: false})
    // } else {
    //   this.setState({defaultDate: true})
    // }
    if (platformSet.platformName) {
      Taro.setNavigationBarTitle({
        title: platformSet.platformName
      })
    }
    await user.checkLogin()
    const userData = await user.getUserData()

    const {
      itemId,
      onlyTicketPay = '0',
      zero = 0,
      meal = '',
      buyDate = '',
      env = '',
      fromOrderNum,
      activityId = '',
      isLeader = false,
      stepNum = 0,
      groupPrice,
      goodUuid,
      limitGoodsId = '',
      goodsDiscountCodeType = '',
      goodsDiscountCodeId = '',
      groupBuyId = '',
      force_platform_seller = '',
      goods_seckill_id = '',
      pageType = ''
    } = Taro.getCurrentInstance().router.params
    Taro.getStorageSync('contactDataStore')
    if (onlyTicketPay === "1") {
      Taro.setStorageSync('onlyTicketPay', 1)
      const contactDataStore = Taro.getStorageSync('contactDataStore')
      if (!contactDataStore) {
        Taro.setStorageSync('contactDataStore', [])
      }
    }
    await this.setStateSync({force_platform_seller, limitGoodsId, goodsDiscountCodeType, goodsDiscountCodeId});
    const tempSellerId = getTempSellerId(this)
    if (!itemId && !fromOrderNum) {
      Taro.showToast({title: '参数错误', icon: 'none'})
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.navigateBack()
      }, 1500)
      return
    }
    let fromGoodDetail
    if (fromOrderNum) {
      fromGoodDetail = await http.postCar(TRANS_ORDER_DETAIL + fromOrderNum, {})
    }
    this.goodId = parseInt(itemId)
    const goodParams = {
      goodsId: itemId,
      useIntegral: false,
      isComments: true
    };
    if(pageType === "limitedSeckill") goodParams.secKillIds = goods_seckill_id
    const goodDetail = await http.get<OrderGoodDetail>(ORDER_GOOD_DETAIL, goodParams)

    this.setState({
      isLeader: Number(JSON.parse(isLeader)),
      goodUuid,
      onlyTicketPay,
      zero,
      mealArrId: meal,
      platformSet,
      tempSellerId,
      env,
      agree: !!platformSet.user_agreement_type,
      pageType
    })
    this.getLinkAuto()
    const referSellerId = Taro.getStorageSync('bindSellerId') || 0;
    if (goodDetail) {
      let custom_item_config
      if (fromOrderNum) {
        const custom_item_detail = JSON.parse(fromGoodDetail.custom_item_detail)
        if (custom_item_detail.custom_item_config) {
          fromGoodDetail.is_custom_item = goodDetail.goods.is_custom_item
          custom_item_config = custom_item_detail.custom_item_config
          fromGoodDetail.custom_item_config = JSON.stringify(custom_item_config)
        }
      } else {
        custom_item_config = JSON.parse(goodDetail.goods.custom_item_config)
      }
      for (const k in custom_item_config) {
        if (k.includes('field')) {
          this.state.fieldCustom.push({k: custom_item_config[k].k, ckd: custom_item_config[k].ckd, name: k})
        }
      }
      let userFormData
      if (fromOrderNum) {
        userFormData = this.formatUserFormData(fromGoodDetail)
      } else {
        userFormData = this.formatUserFormData(goodDetail.goods)
      }
      const userForm = this.userInfo ? this.state.userForm : [JSON.parse(userFormData)]
      let newPayOrderIdRet
      const apiPath = pageType !== "limitedSeckill" ? NEW_PAY_CREATE_ORDER + userData.uuid : FETCH_SECKILL_CREATE + userData.uuid
      const params = {
        limit_goods_id: limitGoodsId,
        force_platform_seller,
        goodsDiscountCodeType,
        goodsDiscountCodeId,
        activity_id: activityId,
        group_buy_id: groupBuyId,
        is_leader: Number(JSON.parse(isLeader)),
        step_num: stepNum,
        referSellerId,
        tempSellerId,
        goodsUUID: goodDetail.goods.uuid || ''
      }
      if(pageType === "limitedSeckill") params.goods_seckill_id = goods_seckill_id
      newPayOrderIdRet = await newHttp.post(apiPath, params, true);
      const checkmeal = Taro.getStorageSync("checkmeal") || []
      const meals = []
      if (checkmeal.length > 0) {
        checkmeal.map((item: any) => {
          if (meal.indexOf(item.id) > -1) {
            meals.push(item)
          }
        })
      }
      // 三天日期
      const ThreeDayCalendar = goodDetail.ThreeDayCalendar
      for (const i in goodDetail.ThreeDayCalendar) {
        const showDate = goodDetail.ThreeDayCalendar[i].date.split('-')
        ThreeDayCalendar[i].showDate = showDate[1] + '-' + showDate[2]
      }
      await this.setState({
        activityId,
        threeDate: ThreeDayCalendar,
        goodDetail,
        fromGoodDetail,
        userForm,
        userFormTemplate: userFormData,
        meals,
        custom_item_config,
        fieldCustom: this.state.fieldCustom,
        showLoading: false,
        newPayOrderIdRet
      }, async () => {
        this.linkData(fromOrderNum ? fromGoodDetail : goodDetail.goods)
        await this.getData(goodDetail, buyDate, platformSet, newPayOrderIdRet)
      })
    }
    this.isIPhoneX()
  }

  setStateSync(state) {
    return new Promise(resolve => {
      this.setState(state, resolve);
    });
  }

  // 组织出行人数据
  async linkData(list) {
    let _contactData = []
    let {linkDataList, openTraveler, onlyTicketPay} = this.state
    const listData = list
    const config = []
    const custom_item_config = JSON.parse(listData.custom_item_config)
    for (const k in custom_item_config) {
      if (custom_item_config[k]) config.push(k)
    }
    let data = []
    if (onlyTicketPay === '1') {
      data = Taro.getStorageSync('contactDataStore')
    } else {
      data = await http.carGet(GET_LINK_INFO_LIST, {
        config,
        goodsId: listData.id,
        is_custom_item: list.is_custom_item
      })
    }
    if (data) {
      for (const k in data) {
        data[k].value = typeof data[k].value === 'object' ? data[k].value : JSON.parse(data[k].value)
        data[k].value[0]['checked'] = false
        data[0].value[0]['num'] = 1
      }
      const newArr = []
      for (const k in custom_item_config) {
        if (custom_item_config[k]) {
          newArr.push(custom_item_config[k])
        }
      }
      openTraveler = newArr.length > 0
      if (data && data.length === 0 && custom_item_config['name'] === false && custom_item_config['phone'] === false) {
        _contactData = [
          [{
            "id": '',
            "uuid": "",
            "value":
              [
                {
                  "address": "",
                  "comments": "",
                  "city": "",
                  "num": 1,
                  "upload_file": "",
                  "face": "",
                  "province": "",
                  "phone": "17700000000",
                  "idcard": "",
                  "name": "-",
                  "checked": true,
                  "region": "",
                  "isInfo": false,
                  "mark": ""
                }
              ],
            "field": "name,phone"
          }]
        ]
        linkDataList.push(_contactData[0][0]['value'][0])
        linkDataList[0].isInfo = this.linkIsInfo(0)
      } else {
        _contactData.push(data)
        if (_contactData[0].length >= 0) {
          if (_contactData[0].length >= 1) {
            _contactData[0][0]['value'][0]['checked'] = true
            linkDataList.push(_contactData[0][0]['value'][0])
            linkDataList[0].isInfo = this.linkIsInfo(0)
          } else {
            linkDataList.push('')
          }
        }
      }
      const strContactData = JSON.stringify(_contactData)
      this.setState({
        contactData: JSON.parse(strContactData),
        linkDataList,
        showLoadingLink: false,
        openTraveler
      }, () => {
        this.getLinkAuto()
      })
    }
  }

  // 联系人是否需要补全信息
  linkIsInfo(index) {
    const {goodDetail, linkDataList, fromGoodDetail} = this.state
    let config = JSON.parse(goodDetail.goods.custom_item_config)
    if (fromGoodDetail) {
      config = JSON.parse(fromGoodDetail.custom_item_config)
    }
    if (linkDataList[index]) {
      for (const i in config) {
        if (config.address && !linkDataList[index]['province'] && !linkDataList[index]['city'] && !linkDataList[index]['region']) {
          return true
        }
        if (i != 'mark' && i != 'comments') {
          if (i.includes('field')) {
            if (!linkDataList[index][i] && config[i].ckd) {
              return true
            }
          } else if (config[i]) {
            if (!linkDataList[index][i]) {
              return true
            }
          }
        }
      }
    }
    return false
  }

  // 选中联系人
  selectContact(index, idx, num) {
    const {contactData, linkDataList} = this.state
    const _linkDataList = linkDataList
    let arrLen = 0
    for (const i in contactData[index]) {
      if (contactData[index][i]['value'][0]['checked']) arrLen += 1
    }
    if (num !== 1 && arrLen >= num && !contactData[index][idx]['value'][0]['checked']) {
      Taro.showToast({
        title: `此产品仅需添加 ${num} 位出行人信息`,
        icon: 'none',
      })
      return false
    }
    if (num == 1) {
      contactData[index][0]['value'][0]['num'] = 1
      for (const k in contactData[index]) {
        contactData[index][k]['value'][0]['checked'] = false
      }
      _linkDataList[0] = contactData[index][idx]['value'][0]
      linkDataList[0].isInfo = this.linkIsInfo(0)
      // _linkDataList = []
    }

    contactData[index][idx]['value'][0]['checked'] = !contactData[index][idx]['value'][0]['checked']

    if (num > 1) {
      // 选中
      if (contactData[index][idx]['value'][0]['checked']) {
        for (let i = _linkDataList.length - 1; i >= 0; i--) {
          if (_linkDataList[i] == '' || !_linkDataList[i]) {
            _linkDataList[i] = contactData[index][idx]['value'][0]
            linkDataList[i].isInfo = this.linkIsInfo(i)
            break
          }
        }
      } else {
        // 未选中
        for (let i = _linkDataList.length - 1; i >= 0; i--) {
          if (_linkDataList[i].phone == contactData[index][idx]['value'][0]['phone']) {
            _linkDataList.splice(i, 1)
            _linkDataList.unshift('')
          }
        }
      }
    }

    // && num != 1
    if (contactData[index][idx]['value'][0]['checked'] && num != 1) {
      contactData[index][0]['value'][0]['num'] += 1
    } else if (num != 1) {
      contactData[index][0]['value'][0]['num'] -= 1
    }
    if (idx > 2) this.swapArr(contactData, index, idx)
    this.setState({
      contactData,
      oldCtIndex: idx,
      oldFirstIndex: index,
      index: index,
      linkDataList: _linkDataList,
      floatLayoutIdcard: false
    })
  }

  // 联系人删除按钮显示
  showIdcardDel(index, idx) {
    if (this.state.idcardDelIndex != index + '-' + idx) {
      this.state.idcardDelIndex = index + '-' + idx
      this.setState({idcardDelIndex: this.state.idcardDelIndex, idcardDel: this.state.idcardDel})
    } else {
      if (this.state.idcardDelIndex) {
        this.setState({idcardDelIndex: ''})
      } else {
        this.state.idcardDelIndex = index + '-' + idx
        this.setState({idcardDelIndex: this.state.idcardDelIndex, idcardDel: this.state.idcardDel})
      }
    }
  }

  // 删除选中联系人
  delSelectContact(index, idx, num, phone, name) {
    const {contactData, oldCtIndex, linkDataList} = this.state
    contactData[index][0]['value'][0]['num'] -= 1
    for (const k in contactData[0]) {
      if (contactData[0][k]['value'][0]['phone'] == phone && contactData[0][k]['value'][0]['name'] == name) {
        contactData[0][k]['value'][0]['checked'] = false
      }
    }
    linkDataList.splice(num == 1 ? 0 : idx, 1)
    linkDataList.unshift('')

    this.setState({contactData, idcardDelIndex: '', linkDataList})
  }

  // 更新出行人
  async updateContact() {
    const {goodDetail, contactData, layoutIndex, editId, linkDataList, idx, getFee, fromGoodDetail, onlyTicketPay} = this.state
    const config = []
    const custom_item_config = JSON.parse(fromGoodDetail ? fromGoodDetail.custom_item_config : goodDetail.goods.custom_item_config)
    const contactDataL = contactData[0].filter(item => {
      return item.value[0]['checked']
    })
    for (const k in custom_item_config) {
      if (custom_item_config[k]) config.push(k)
    }
    let list = false
    if (onlyTicketPay !== '1') {
      list = await http.carGet(GET_LINK_INFO_LIST, {
        config,
        goodsId: fromGoodDetail ? fromGoodDetail.id : goodDetail.goods.id,
        is_custom_item: goodDetail.goods.is_custom_item
      })
    } else {
      list = Taro.getStorageSync('contactDataStore')
    }
    for (const i in list) {
      list[i].value = typeof list[i].value === 'object' ? list[i].value : JSON.parse(list[i].value)
      if (contactData[layoutIndex][0]) list[0].value[0]['num'] = contactData[layoutIndex][0].value[0]['num']
      else list[0].value[0]['num'] = 0

      if (contactData[layoutIndex][i] && contactDataL.length <= getFee.num) {
        if (contactData[0].length < list.length) {
          list[i].value[0]['checked'] = list[i].checked ? list[i].checked : false
        }
      }
      //新增联系人添加到已选中
      if (list[i].checked) {
        for (let k = linkDataList.length - 1; k >= 0; k--) {
          if (getFee.num == 1) {
            linkDataList[0] = list[i].value[0]
            break;
          } else {
            if (linkDataList[k] == '' || !linkDataList[k]) {
              if (linkDataList.filter(item => {
                return list[i].value[0]['name'] == item.name && list[i].value[0]['phone'] == item.phone
              }).length == 0) {
                linkDataList[k] = list[i].value[0]
                break;
              }
            }
          }
        }
      }
    }
    //编辑联系人更新
    if (editId) {
      const index1 = list.findIndex((value) => value.id == editId);
      if (index1 >= 0) {
        linkDataList[idx] = list[index1]['value'][0]
        linkDataList[idx].isInfo = this.linkIsInfo(idx)
      } else {
        linkDataList[idx] = ''
      }
    }

    for (const l in list) {
      list[l]['value'][0].checked = false
    }
    for (const item in linkDataList) {
      for (const l in list) {
        if (linkDataList[item]['name'] == list[l]['value'][0]['name'] && linkDataList[item]['phone'] == list[l]['value'][0]['phone']) {
          list[l]['value'][0].checked = true
        }
      }
    }
    contactData[layoutIndex] = list
    if (contactData[0].length > 0) contactData[0][0]['value'][0]['num'] = linkDataList.length
    let bottomView = ''
    if (Taro.getStorageSync('addContact')) {
      Taro.removeStorageSync('addContact')
      bottomView = 'bottomView0'
    }
    this.setState({contactData, linkDataList, custom_item_config, bottomView}, () => {
      this.getLinkAuto()
    })
  }

  arrTest(arr, key1, key2) {
    const obj = {};
    for (let i = 0; i < arr.length; i++) {
      if (obj[arr[i][key1]] && obj[arr[i][key2]]) {
        return false;
      } else {
        obj[arr[i]] = arr[i];
      }
    }
    return obj;
  }

  jump(this, index = this.state.layoutIndex, goodsId = this.state.goodDetail.goods.id, config = this.state.fromGoodDetail ? this.state.fromGoodDetail.custom_item_config : this.state.goodDetail.goods.custom_item_config) {
    if (index) {
      this.setState({layoutIndex: index})
    }
    this.setState({editId: ''})
    Taro.removeStorageSync('addcontact')
    Taro.setStorageSync('addcontact', {
      index: index,
      goodsId: goodsId,
      config: config,
      itemId: this.state.itemId,
      page: 'confirm'
    });
    Taro.navigateTo({
      url: '/other/address/addcontact?onlyTicketPay=' + this.state.onlyTicketPay
    })
  }

  newAddJump() {
    const {layoutIndex, itemId, goodDetail, fromGoodDetail} = this.state
    Taro.removeStorageSync('addcontact')
    Taro.setStorageSync('addcontact', {
      index: layoutIndex,
      goodsId: fromGoodDetail ? fromGoodDetail.id : goodDetail.goods.id,
      config: fromGoodDetail ? fromGoodDetail.custom_item_config : goodDetail.goods.custom_item_config,
      itemId: itemId,
      page: 'confirm'
    });
    Taro.navigateTo({
      url: '/other/address/addcontact?onlyTicketPay=' + this.state.onlyTicketPay
    })
  }

  edit(index, idx, goodsId, config, phone, name) {
    let editId = ''
    let goodsUuid = ''
    for (const k in this.state.contactData[0]) {
      if (this.state.contactData[0][k]['value'][0].phone == phone && this.state.contactData[0][k]['value'][0].name == name) {
        goodsUuid = this.state.contactData[0][k].uuid
        editId = this.state.contactData[0][k].id
        this.state.delIndex = k
      }
    }
    this.setState({layoutIndex: index, idx, editId, delIndex: this.state.delIndex})
    Taro.removeStorageSync('addcontact')
    Taro.setStorageSync('addcontact', {
      idx: idx,
      index: index,
      goodsUuid: goodsUuid,
      goodsId: goodsId,
      config: config,
      itemId: this.state.itemId,
      isSave: true,
      page: 'confirm'
    });
    Taro.navigateTo({
      url: '/other/address/addcontact?onlyTicketPay=' + this.state.onlyTicketPay
    })
  }

  async getData(goodDetail, buyDate, platformSet, newPayOrderIdRet) {
    const {fromGoodDetail, feeInfo} = this.state
    const step = this.getStep(goodDetail.goods)
    if (goodDetail.goods.category == 2) {
      this.setState({
        booking_day_end: goodDetail.goods.booking_day_end ? goodDetail.goods.booking_day_end : 0,
        booking_time_end: goodDetail.goods.booking_time_end ? goodDetail.goods.booking_time_end : '23:59:00',
      })
    }
    if (process.env.TARO_ENV === 'weapp') {
      // 检查用户有没有授权头像手机号
      const userOk = await user.checkUserInfo()
      if (userOk == 2) {
        Taro.login().then(async code => {
          user.code = code.code
          const ret = await user.doLogin({
            nickName: '',
            gender: 1,
            language: '',
            city: '',
            province: '',
            country: '',
            avatarUrl: '',
            bindSellerId: 0,
            itemUUID: '',
            path: ''
          })
          if (!ret) {
            Taro.showToast({
              title: '授权失败,请退出小程序重试',
              icon: 'none'
            })
            return
          }
        })
      }
      this.setState({userOk, thisBuyDate: buyDate})
    } else {
      this.setState({thisBuyDate: buyDate})
    }
    const goodsGroup: { good_id: number; num: number; name: string; buy_num_min: number; buy_num_max: number; tips_msg?: any; opentips?: boolean }[] = []
    const that = this
    let startDate = this.props.selectDate.start
    if (buyDate) {
      startDate = buyDate
    } else if (goodDetail.goods.travel_date_style && goodDetail.goods.category !== 2) {
      startDate = goodDetail.goods.EffectiveDateStr
    }
    const date = this.initDate ? this.state.buyDate : {
      start: startDate,
      end: this.props.selectDate.end
    }
    this.initDate = true;
    const getFee = this.state.getFee;
    getFee.num = goodDetail.goods.buy_num_min ? goodDetail.goods.buy_num_min : 1
    if (goodDetail.goods.buy_num_min) getFee.buy_num_min = goodDetail.goods.buy_num_min
    if (goodDetail.goods.buy_num_max) getFee.buy_num_max = goodDetail.goods.buy_num_max
    if (platformSet && platformSet.payVersion === 1) {
      if (newPayOrderIdRet && newPayOrderIdRet.data) {
        const newPayOrderId = newPayOrderIdRet.data;
        this.setState({
          step,
          goodsGroup,
          newPayOrderId,
          platformSet,
          useIntegral: goodDetail.goods.is_auto_use_integral == 1,
          buyDate: date,
          getFee,
        }, async () => {
          const days = await this.getDaysBetween(date.start, date.end)
          const feeInfo = await that.getFee(false)
          if (this.state.recharge && platformSet.payVersion === 1) {
            if (feeInfo.userBalance >= feeInfo.totalFee) {
              this.setState({canBalance: true})
            } else {
              this.setState({canBalance: false})
            }
          }
          if (goodDetail.goods.is_auto_use_integral == 1) {
            getFee.jf = feeInfo.jf
          }
          this.setState({feeInfo, days}, async () => {
            this.getSelectorQuery() //套餐dom高度
            if (feeInfo) {
              if (goodDetail.goods.type === 1 && goodDetail.goods.category !== 4 && goodDetail.goods.category !== 5) {
                if (goodDetail.goods.category) {
                  await this.initCalendatData(goodDetail)
                }
              } else {
                if (goodDetail.goods.category !== 4) {
                  if (feeInfo && !goodDetail.goods.category) {
                    const val = feeInfo.maxJf <= goodDetail.integral.score ? feeInfo.maxJf : goodDetail.integral.score
                    if (val) {
                      this.integralChange(val)
                    }
                  } else {
                    this.integralChangeFrist(feeInfo)
                  }
                }
              }
            }
          })
        })
        if (fromGoodDetail) {
          const {getFee} = this.state
          getFee['num'] = fromGoodDetail.buy_amount
          feeInfo['totalFee'] = fromGoodDetail.trans_price
          this.setState({canBalance: false, feeInfo, getFee})
          return
        }
      } else {
        Taro.showModal({
          title: '提示',
          content: newPayOrderIdRet.message || '获取订单失败',
          showCancel: false,
          confirmText: '知道了',
          success(res) {
            Taro.navigateBack({
              delta: 1
            })
          }
        })
      }
    }
  }

  async componentDidShow() {
    const {upFee, getFee, submiting, payEnd, fromGoodDetail} = this.state
    if (!fromGoodDetail) {
      if (upFee) {
        const redbagId = Taro.getCurrentInstance().page.data.redbagId || 0
        const redbag = Taro.getCurrentInstance().page.data.redbag || false
        if (!submiting && !payEnd) {
          if (redbagId || redbag) {
            getFee.hongbaoId = redbagId;
            this.setState({redbag, redbagId, getFee}, async () => {
              const feeInfo = await this.getFee()
              if (feeInfo) {
                this.setState({feeInfo})
              }
            })
          } else {
            const feeInfo = await this.getFee()
            if (feeInfo) {
              this.setState({feeInfo})
            }
          }
        }
        this.setState({upFee: false})
      }
    }
    if (this.state.goodDetail) {
      this.updateContact()
    }
  }

  async getFee(loading = true, toast = true) {
    await this.setStateSync({submiting: true})
    const {fromOrderNum} = Taro.getCurrentInstance().router.params
    const {buyDate, useIntegral, newPayOrderId, mealArrId, goodDetail, getFee} = this.state
    if (newPayOrderId) {
      const platformSet = await platform.getSetting()
      const data: GetFeeType = {
        ...getFee,
        goodsId: this.goodId,
        dateRange: JSON.stringify({start: buyDate.start, end: buyDate.end}),
        startDate: buyDate.start,
        endDate: buyDate.end,
        buyDate: buyDate.start,
        goodsGroup: this.state.goodsGroup.length > 0 ? JSON.stringify(this.state.goodsGroup) : '',
        couponIsuseId: fromOrderNum ? 0 : this.state.feeInfo.couponIsuseId || 0,
        useIntegral,
      }
      if (data.useIntegral) {
      } else {
        data.jf = 0
      }
      if (mealArrId) {
        data['mealArrId'] = mealArrId
      }
      let ret: boolean | GetFeeType = false;
      if (platformSet.payVersion === 1) {
        const r = process.env.P_ENV === 'lx' ? await newHttp.get_lxMerge(NEW_PAY_PARAMS + newPayOrderId, data, true) : await newHttp.get(NEW_PAY_PARAMS + newPayOrderId, data, true);
        if (r.data && r.data.couponIsuseId) {
          let couponMoneyName = ''
          let couponMoney = ''
          let notUse = true
          r.data.coupon_list.map(item => {
            if (item.id === +r.data.couponIsuseId) {
              notUse = false
              couponMoneyName = item.amount_limit_str
              couponMoney = item.coupon_discounts_money
            }
          })
          data.couponIsuseId = +r.data.couponIsuseId
          this.setState({couponMoneyName, couponMoney, notUse})
        }
        await this.setStateSync({submiting: false})
        const that = this
        setTimeout(function () {
          that.setState({disable: false})
        }, 500);
        if (r && r.data) {
          Taro.hideLoading()
          ret = r.data || false;
          if (goodDetail.goods.is_auto_use_integral == 1 || getFee.jf > ret.maxJf) {
            getFee.jf = ret.maxJf
            that.setState({getFee})
          }
        } else {
          Taro.hideLoading()
          ret = false;
          if (toast) {
            const {message} = r
            if (message.indexOf("deed") > -1) {
              const {goods: {type, category}} = goodDetail
              if (type === 1 && category !== 4 && category !== 5 && category !== 2) {
                if (category) {
                  that.initCalendatData(goodDetail)
                }
              }
              if (category === 2) {
                Taro.showModal({
                  title: '提示',
                  content: message.replace("deed", '') || '',
                  success(res) {
                    if (res.confirm) {
                      Taro.navigateBack({
                        delta: 1
                      })
                    } else if (res.cancel) {
                      Taro.navigateBack({
                        delta: 1
                      })
                    }
                  }
                })
              }
            } else {
              Taro.showToast({
                title: r.message || '',
                icon: 'none',
                duration: 2500,
              })
            }

          } else {
            Taro.hideLoading()
          }
        }
      } else {
        const r = await http.postCondition<ServerData<GetFeeType>>(GET_FEE, data);
        const that = this
        setTimeout(function () {
          Taro.hideLoading()
          that.setState({disable: false})
        }, 500);
        if (r) {
          ret = r.data
        } else {
          ret = false
        }
      }
      return ret
    } else {
      return false
    }
  }

  inputEvent(e) {
    if (e.detail.value) {
      this.inputNumber(e.detail.value)
    } else {
      Taro.showToast({
        title: '数量不能为零',
        icon: "none"
      })
    }
  }

  iosScroll() {
    if (TARO_ENV === 'h5') {
      const u = navigator.userAgent
      const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
      if (isIOS) {
        setTimeout(() => {
          const data = document.querySelector('.footer-btn').offsetTop
          document.getElementsByClassName('footer-btn').cssText = 'position:fixed;bottom:0;left:0'
          document.querySelector('.footer-btn').scrollTo(0, data)
          const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0
          window.scrollTo(0, Math.max(scrollHeight - 1, 0))
        }, 100)
      }
    }
  }

  inputNumber(num) {
    if (num < 0) {
      Taro.showToast({title: '数量不能小于0', icon: "none"})
      return
    }
    const {goodDetail, feeInfo, getFee, linkDataList, contactData, custom_item_config} = this.state
    Taro.showLoading({title: '计算中...', mask: true})
    const linkDataListL = linkDataList.length
    if (num > 0 && goodDetail.goods.is_custom_item > 0) {
      if (this.state.oldNum > num) {
        for (let i = 0; i < (linkDataListL - num); i++) {
          linkDataList.shift()
        }
      }
      if (this.state.oldNum < num) {
        for (let i = 0; i < (num - linkDataListL); i++) {
          if (custom_item_config['name'] === false && custom_item_config['phone'] === false) {
            contactData[0].push(
              {
                "id": '',
                "uuid": "",
                "value":
                  [
                    {
                      "address": "",
                      "comments": "",
                      "city": "",
                      "num": 1,
                      "upload_file": "",
                      "face": "",
                      "province": "",
                      "phone": "17700000000",
                      "idcard": "",
                      "name": "-",
                      "checked": true,
                      "region": "",
                      "isInfo": false,
                      "mark": ""
                    }
                  ],
                "field": "name,phone"
              }
            )
            linkDataList.unshift(contactData[0][0]['value'][0])
          } else {
            linkDataList.unshift('')
          }
        }
      }
    }
    const oldNum = num
    for (const l in contactData[0]) {
      contactData[0][l]['value'][0]['checked'] = false
    }
    for (const item in linkDataList) {
      for (const l in contactData[0]) {
        if (linkDataList[item]['name'] == contactData[0][l]['value'][0]['name'] && linkDataList[item]['phone'] == contactData[0][l]['value'][0]['phone']) {
          contactData[0][l]['value'][0]['checked'] = true
        }
      }
    }
    if (num && goodDetail && num !== getFee.num) {
      if (goodDetail.goods.is_auto_use_integral == 0 && goodDetail.goods.exchange_type == 1) {
        if (num < getFee['num']) {
          let proJf = Math.ceil(num * Number(feeInfo.proJf))
          proJf = proJf < goodDetail.integral.score ? proJf : goodDetail.integral.score
          getFee['jf'] = getFee.jf < proJf ? getFee.jf : proJf
        }
      }
      getFee['num'] = num
      let newUserForm = this.state.userForm
      if (this.state.goodDetail && this.state.goodDetail.goods.is_custom_item === 2) {
        const userForm = this.state.userForm
        const userFormTemplate = JSON.parse(this.state.userFormTemplate)
        if (num < userForm.length) {
          if (num >= 1) {
            newUserForm = userForm.slice(0, num)
          }
        } else {
          for (let i = userForm.length; i < num; i++) {
            userForm.push(userFormTemplate)
            newUserForm = userForm
          }
        }
      }
      if (this.state.goodDetail && this.state.goodDetail.goods.is_custom_item === 1) {
        const userForm = this.state.userForm
        if (num < userForm.length) {
          if (num >= 1) {
            newUserForm = userForm.slice(0, num)
          }
        }
      }
      const flAry = []
      for (let i = 0; i < Number(getFee.num); i++) {
        flAry.push('')
      }
      this.setState({getFee, flAry, userForm: newUserForm, linkDataList, oldNum}, async () => {
        const feeInfo = await this.getFee()
        getFee.buy_num_max = feeInfo.buy_num_max
        getFee.buy_num_min = feeInfo.buy_num_min
        getFee.num = feeInfo.num ? feeInfo.num : getFee.num
        if (feeInfo) {
          if (goodDetail.goods.is_auto_use_integral == 1 && goodDetail.goods.category !== 4) {
            if (feeInfo.maxJf) {
              getFee['jf'] = feeInfo.maxJf
            }
          }
          this.setState({feeInfo, getFee})
        }
      })
    } else {
      Taro.hideLoading()
    }
    this.iosScroll()
  }

  inputChange(index, type, value) {
    this.userInfo = true
    const userForm = this.state.userForm
    userForm[index][type].value = value
    this.setState({userForm})
  }

  inputGroupNumber(id, num) {
    const goodsGroup = this.state.goodsGroup.map(item => {
      if (item.good_id === id) {
        item.num = parseInt(num)
      }
      return item
    })
    this.setState({goodsGroup}, async () => {
      const feeInfo = await this.getFee()
      if (feeInfo) {
        this.setState({feeInfo})
      }
    })
  }

  integralChangeFrist(feeInfo) {
    const {goodDetail} = this.state
    const getFee = this.state.getFee
    if (goodDetail.goods.is_auto_use_integral == 1) {
      getFee.jf = feeInfo.jf
    }
    this.setState({getFee})
  }

  integralChange(value) {
    const {goodDetail} = this.state
    const getFee = this.state.getFee
    if (goodDetail.goods.is_auto_use_integral == 1) {
      getFee.jf = value
      this.setState({getFee}, async () => {
        const feeInfo = await this.getFee()
        if (feeInfo) {
          this.setState({feeInfo})
        }
      })
    }
  }

  integralChangebtn(value) {
    //btn 为1 的时候为用户操作
    const {goodDetail, getFee} = this.state
    Taro.showLoading({title: '计算中...', mask: true})
    let newFee = null
    getFee['jf'] = value
    newFee = JSON.stringify(getFee)
    this.setState({getFee: JSON.parse(newFee)}, async () => {
      const feeInfo = await this.getFee()
      if (feeInfo) {
        this.setState({feeInfo})
      }
    })
  }

  integralChangebtnKD(value) {
    //btn 为1 的时候为用户操作
    const {goodDetail, getFee} = this.state
    Taro.showLoading({title: '计算中...', mask: true})
    let newFee = null
    getFee['consume_fee'] = value.toString().match(/^\d+(?:\.\d{0,2})?/)[0]
    newFee = JSON.stringify(getFee)
    this.setState({getFee: JSON.parse(newFee)}, async () => {
      const feeInfo = await this.getFee()
      if (feeInfo) {
        this.setState({feeInfo})
      }
    })

  }

  regionChange(e) {
    const {payData} = this.state
    payData.province = e.detail.value[0]
    payData.city = e.detail.value[1]
    payData.region = e.detail.value[2]
    this.setState({payData})
  }

  isIPhoneX() {
    try {
      const res = Taro.getSystemInfoSync()
      if (res.model == 'iPhone X') {
        this.setState({isiPhonex: true})
      }
    } catch (e) {
      // Do something when catch error
    }
  }

  integralSwitchKD(val) {
    const {openKD, getFee} = this.state
    if (!openKD) {
      this.setState({openKD: true})
    } else {
      getFee['consume_fee'] = 0
      this.setState({openKD: false, getFee}, async () => {
        const feeInfo = await this.getFee()
        if (feeInfo) {
          this.setState({feeInfo})
        }
      })
    }
  }

  integralSwitch(value: boolean): void {
    if (this.state.alldisable) {
      return
    }
    if (this.state.goodDetail) {
      const integral = this.state.goodDetail.integral
      const good = this.state.goodDetail.goods
      if (!integral.can) {
        Taro.showToast({title: '当前产品不可使用' + getGlobalData(), icon: 'none'})
        this.setState({useIntegral: false})
        return
      }
      if (good.exchange_type === 2 && integral.score < integral.max) {
        Taro.showToast({title: getGlobalData() + '余额不足', icon: 'none'})
        this.setState({useIntegral: false})
        return
      }
      if (good.exchange_type === 2) {
        const getFee = this.state.getFee
        if (value) {
          getFee['jf'] = integral.exchangeMaxIntegral
          getFee.useIntegral = true
        } else {
          getFee['jf'] = 0
          getFee.useIntegral = false
        }
        this.setState({useIntegral: value, getFee}, async () => {
          const feeInfo = await this.getFee()
          if (feeInfo) {
            this.setState({feeInfo})
          }
        })
        this.setState({useIntegral: value})
      } else {
        const getFee = this.state.getFee
        this.setState({useIntegral: value, getFee, indextime: 1}, async () => {
          const feeInfo = await this.getFee()
          if (feeInfo) {
            this.setState({feeInfo})
          }
        })

        this.setState({useIntegral: value})
      }

    }

  }

  async getPhoneNumber(data) {
    const {payData} = this.state
    try {
      if (data && data.detail && data.detail.errMsg.indexOf('ok') > -1) {
        const res = await http.post(GET_PHONE, {encryptedData: data.detail.encryptedData, iv: data.detail.iv})
        if (res) {
          if (!payData['phone']) {
            payData['phone'] = res.phoneNumber
          }
          this.setState({userOk: 1, payData})
          Taro.showToast({title: '授权成功！'})
        } else {
          Taro.showModal({
            title: '提示',
            content: '需要获取手机号，请打开"使用我的用户信息", 然后再点击登录',
            success: (res) => {
              if (res.confirm) {
                Taro.openSetting()
              } else {
                Taro.navigateBack({
                  delta: 1
                })
              }
            }
          })
          console.log('getPhoneNumber: fail')
        }
      } else {
        user.logout()
      }
    } catch (error) {
      console.error(error)
    }
  }

  userInfo = false

  async getUserInfo() {
    if (this.state.alldisable) {
      return false;
    }
    Taro.showLoading({title: '获取中...'})
    const userInfo = await http.post<DefaultInfo>(GET_DEFAULT_INFO, {})
    if (userInfo) {
      const {userForm} = this.state
      const userFormTemplate = JSON.parse(this.state.userFormTemplate)
      userFormTemplate.name.require ? userForm[0].name.value = userInfo.name : ''
      userFormTemplate.phone.require ? userForm[0].phone.value = userInfo.phone : ''
      if (userFormTemplate.comments) {
        if (userInfo.comments) {
          userFormTemplate.comments.require ? userForm[0].comments.value = userInfo.comments : ''
        }
      }
      userFormTemplate.idcard.require ? userForm[0].idcard.value = userInfo.identify_num : ''
      userFormTemplate.region.require ? userForm[0].region.value = [userInfo.delivery_province, userInfo.delivery_city, userInfo.delivery_area] : ''
      userFormTemplate.region.require ? userForm[0].address.value = userInfo.address : ''
      this.userInfo = true
      this.setState({userForm})
    }
    setTimeout(() => {
      Taro.hideLoading()
    }, 100)
  }

  customChange(index, n, value) {
    const userForm = this.state.userForm
    const val = value.replace(/\s*/g, "");
    userForm[index].custom[n].value = val
    this.setState({userForm})
  }

  addPerson() {
    if (this.state.alldisable) {
      return
    }
    const userForm = this.state.userForm
    userForm.push(JSON.parse(this.state.userFormTemplate))
    this.setState({userForm})
  }

  // 获取联系人姓名手机号
  async getLinkAuto() {
    const {payData, contactData, custom_item_config} = this.state
    let data = await http.carGet(GET_DEFAULT_INFO)
    let linkShow = false
    if (!data) {
      data = {
        name: '',
        face: '',
        phone: ''
      }
      payData.name = data.name
      payData.phone = data.phone
      payData.face = data.face
    }
    if (data.phone && data.name) {
      payData.name = data.name
      payData.phone = data.phone
      payData.face = data.face
    } else if (contactData && contactData.length > 0 && contactData[0].length > 0) {
      payData.name = contactData[0][0]['value'][0]['name']
      payData.phone = contactData[0][0]['value'][0]['phone']
      payData.face = contactData[0][0]['value'][0]['face']
    }
    if (custom_item_config['name'] === false) {
      payData.name = '-'
    }
    if (custom_item_config['phone'] === false) {
      payData.phone = '13700000000'
    }

    if (payData.name === '-' || payData.phone === '13700000000' || payData.phone === '17700000000') {
      linkShow = true
    }
    this.setState({payData, linkShow})
  }

  async submitCheck(feeInfo) {
    const {
      onlyTicketPay,
      fromGoodDetail,
      agree,
      linkDataList,
      goodDetail,
      custom_item_config,
      fieldCustomError,
      submiting,
      getFee,
      platformSet,
      assembling_place,
      contactData,
      payData,
      defaultDate
    } = this.state
    if (!defaultDate && !!goodDetail.goods.category && goodDetail.goods.category != 5 && goodDetail.goods.category != 2 && goodDetail.goods.is_open != 0) {
      Taro.showToast({title: '请选择出行日期', icon: 'none'})
      return false
    }
    if (!agree) {
      Taro.showToast({title: '请仔细阅读并同意服务条款', icon: 'none'})
      return false
    }
    if (custom_item_config['name'] && custom_item_config['name'] === true && payData.name === '-') {
      Taro.showToast({title: '请修改联系人信息', icon: "none"})
      return
    }
    if (custom_item_config['phone'] && custom_item_config['phone'] === true && (payData.phone === '13700000000' || payData.phone === '17700000000')) {
      Taro.showToast({title: '请修改联系人信息', icon: "none"})
      return
    }
    const good = fromGoodDetail || this.state.goodDetail.goods
    if (goodDetail.goods.is_custom_item === 0 && contactData[0].length === 0) {
      for (const k in custom_item_config) {
        if (k !== 'mark') {
          if (typeof custom_item_config[k] != "object" && custom_item_config[k]) {
            if (!payData[k] || payData[k].length == 0) {
              Taro.showToast({title: fieldCustomError[k], icon: 'none'})
              return
            }
            if (custom_item_config['address'] && (!payData['province'] || !payData['city'] || !payData['region'])) {
              Taro.showToast({title: '请选择省市区', icon: 'none'})
              return
            }
          } else if (typeof custom_item_config[k] == "object") {
            if (custom_item_config[k].ckd && !payData[k]) {
              Taro.showToast({title: '请填写必填项', icon: 'none'})
              return
            }
          }
        }
      }
    } else {
      if (custom_item_config) {
        for (const k in custom_item_config) {
          if (k === 'comments' && custom_item_config[k] && !payData[k]) {
            Taro.showToast({title: '请填写必填项', icon: 'none'})
            return
          }
        }
      }
      for (let i = 0; i < linkDataList.length; i++) {
        if (linkDataList[i].isInfo) {
          return Taro.showToast({title: `请补全出行人信息`, icon: "none"})
        }
      }
      if (contactData.length == 0) {
        Taro.showToast({title: `至少添加1位出行人`, icon: "none"})
        return false
      } else {
        const linkNum = contactData[0].filter(item => item.value[0].checked).length
        if (getFee.num == 0) {
          Taro.showToast({title: '购买数量不能为0', icon: 'none'})
          return false
        }
        if (good.is_custom_item != 2 && good.is_custom_item != 1) {
          if (contactData[0].length < 1 || linkNum < 1 || !linkNum) {
            Taro.showToast({title: `至少添加1位出行人`, icon: "none"})
            return false
          }
        } else {
          // 没有出行人选项
          if (contactData[0].length < 1) {
            Taro.showToast({title: `还需添加 1 位出行人`, icon: "none"})
            return false
          }
          // 有出行人选项
          if ((getFee.num > linkNum) || !linkNum) {
            Taro.showToast({
              title: `还需添加 ${getFee.num - linkNum} 位出行人`,
              icon: "none"
            })
            return false
          }
        }
        if (good.is_custom_item == 1) {
          const arr = contactData[0].filter(item => {
            return item['value'][0]['checked']
          })
          if (arr.length == 0) {
            Taro.showToast({title: `还需添加 1 位出行人`, icon: "none"})
            return false
          }
        }
      }
    }
    if (submiting) {
      Taro.showToast({title: '处理中...', icon: 'loading'})
      return false
    }
    let validate = true
    if (goodDetail.goods.is_custom_item > 0) {
      if (!payData.name || !payData.phone) {
        Taro.showToast({title: '请输入联系人信息', icon: "none"})
        validate = false
      }
      const r = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;　　//1开头0-9内十位数
      if (!r.test(payData.phone)) {
        Taro.showToast({title: '手机号码格式不正确', icon: 'none'})
        validate = false
      }
    }
    if (good.category == 3 && good.assembling_place_list && good.assembling_place_list.length > 0) {
      if (!assembling_place) {
        Taro.showToast({title: '请选择集合地点', icon: 'none'})
        this.setState({submiting: false})
        validate = false
      }
    }
    if (!validate) return false
    if (onlyTicketPay === '1') {
      return this.setState({welfare: true})
    }
    if (fromGoodDetail) {
      this.submit(9999)
      return
    }
    if (feeInfo.totalFee == 0 || feeInfo.totalFee == 0.00) {
      this.submit(6666) // 0元
      return
    }
    if (platformSet.payVersion === 1) {
      if (process.env.P_ENV === 'lx') {
        if (good.can_use_conversion_code || feeInfo.creditAmount) {
          this.setState({userBalance: true})
        } else {
          this.submit(0)
        }
        return false
      }
      if (process.env.P_ENV === 'kd' && feeInfo.userCoinBalance >= feeInfo.totalFee) {
        return this.setState({userBalance: true})
      }
      if (feeInfo.userBalance >= feeInfo.totalFee) {
        this.setState({userBalance: true})
      } else if (feeInfo.userBalance == 0 && !good.can_use_conversion_code && !feeInfo.creditAmount) {
        this.submit(0)
      } else {
        this.setState({userBalance: true})
      }
    } else {
      this.submit(0)
    }
  }

  async zeroBuy(data) {
    this.setState({alldisable: true})
    Taro.showLoading({
      title: '排队领取中'
    })
    const result = await newHttp.put(NEW_ZERO_PAY + data.newPayOrderId, data);
    Taro.hideLoading()
    if (result.statusCode === 200) {
      Taro.showToast({title: '领取成功！', mask: true, duration: 2000})
      setTimeout(function () {
        Taro.redirectTo({url: '/main/order/order?status=-1'})
      }, 2000)
    } else {
      this.setState({submiting: false, alldisable: false})
      Taro.showToast({
        title: result.data.message || result.data.msg || '',
        icon: 'none',
        duration: 3000
      })
      setTimeout(function () {
        if (result.data.status != '999') {
          Taro.redirectTo({url: '/main/order/order?status=0'})
        }
      }, 2500)
    }
  }

  sureCheckClose() {
    this.setState({userBalance: false})
  }

  handleClose() {
    this.setState({userBalance: false})
  }

  payFn(f) {
    if (f == 2) {
      const {flAry} = this.state
      const flAryIndex = flAry.indexOf('')
      if (flAryIndex > -1) {
        this.setState({flAryIndex})
        return
      } else {
        this.setState({flAryIndex})
      }
    } else {
      this.setState({userBalance: false})
    }
    this.submit(f)
  }

  async submit(useAccountPay) {
    const {
      onlyTicketPay,
      goodUuid,
      linkDataList,
      activityId,
      goodDetail,
      fieldCustomError,
      custom_item_config,
      contactData,
      getFee,
      submiting,
      newPayOrderId,
      feeInfo,
      zero,
      assembling_place,
      newPayOrderIdRet,
      mealArrId,
      flAry,
      payData
    } = this.state
    const good = this.state.goodDetail.goods
    if (submiting) {
      Taro.showToast({title: '处理中...', icon: 'loading'})
      return false
    }
    if (goodDetail.goods.is_custom_item === 0 && contactData[0].length === 0) {
      for (const k in custom_item_config) {
        if (k !== 'mark') {
          if (typeof custom_item_config[k] != "object" && custom_item_config[k]) {
            if (!payData[k] || payData[k].length == 0 || payData[k] == '') {
              Taro.showToast({title: fieldCustomError[k], icon: 'none'})
              return
            }
            if (custom_item_config['address'] && (!payData['province'] || !payData['city'] || !payData['region'])) {
              Taro.showToast({title: '请选择省市区', icon: 'none'})
              return
            }
          } else if (typeof custom_item_config[k] == "object") {
            if (custom_item_config[k].ckd && !payData[k]) {
              Taro.showToast({title: '请填写必填项', icon: 'none'})
              return
            }
          }
        }
      }
    } else {
      if (custom_item_config) {
        for (const k in custom_item_config) {
          if (k === 'comments' && custom_item_config[k] && !payData[k]) {
            Taro.showToast({title: '请填写必填项', icon: 'none'})
            return
          }
        }
      }
      for (let i = 0; i < linkDataList.length; i++) {
        if (linkDataList[i].isInfo) {
          return Taro.showToast({title: `请补全出行人信息`, icon: "none"})
        }
      }
      if (contactData.length == 0) {
        Taro.showToast({title: `至少添加1位出行人`, icon: "none"})
        return false
      } else {
        const linkNum = contactData[0].filter(item => item.value[0].checked).length
        if (getFee.num == 0) {
          Taro.showToast({title: '购买数量不能为0', icon: 'none'})
          return false
        }

        if (good.is_custom_item != 2 && good.is_custom_item != 1) {
          if (contactData[0].length < 1 || linkNum < 1 || !linkNum) {
            Taro.showToast({title: `至少添加 1 位出行人`, icon: "none"})
            return false
          }
        } else {
          // 没有出行人选项
          if (contactData[0].length < 1) {
            Taro.showToast({title: `还需添加 1 位出行人`, icon: "none"})
            return false
          }
          // 有出行人选项
          if ((getFee.num > linkNum) || !linkNum) {
            Taro.showToast({
              title: `还需添加 ${getFee.num - linkNum} 位出行人`,
              icon: "none"
            })
            return false
          }
        }
        if (good.is_custom_item == 1) {
          const arr = contactData[0].filter(item => {
            return item['value'][0]['checked']
          })
          if (arr.length == 0) {
            Taro.showToast({title: `还需添加 1 位出行人`, icon: "none"})
            return false
          }
        }
      }
    }

    if (submiting) {
      Taro.showToast({title: '处理中...', icon: 'loading'})
      return false
    }
    let validate = true
    if (goodDetail.goods.is_custom_item > 0) {
      if (!payData.name || !payData.phone) {
        Taro.showToast({title: '请输入联系人信息', icon: "none"})
        validate = false
      }
      const r = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;　　//1开头0-9内十位数
      if (!r.test(payData.phone)) {
        Taro.showToast({title: '手机号码格式不正确', icon: 'none'})
        validate = false
      }
    }
    if (good.category == 3 && good.assembling_place_list && good.assembling_place_list.length > 0) {
      if (!assembling_place) {
        Taro.showToast({title: '请选择集合地点', icon: 'none'})
        this.setState({submiting: false})
        validate = false
      }
    }
    if (!validate) return false
    const that = this
    if (onlyTicketPay === '1') {
      useAccountPay = 2
    }
    this.setState({submiting: true}, async () => {
      const data = this.makeFormData();
      if (data) {
        data['payToken'] = feeInfo.payToken || '';
        data['newPayOrderId'] = newPayOrderId;
        data['useAccountPay'] = useAccountPay
        data['tempSellerId'] = this.state.tempSellerId
        if (process.env.P_ENV === 'kd') {
          data.consume_fee = getFee['consume_fee']
        }
        // data['consume_fee'] = getFee['consume_fee']
        if (mealArrId) {
          data['mealArrId'] = mealArrId
        }
        if (zero == 1) {
          this.zeroBuy(data)
          return false
        }
        if (useAccountPay === 6666) {
          const result = await payment.orderPay(data)
          if (result) {
            if (activityId) {
              Taro.showLoading({title: '加载中...'})
              setTimeout(async () => {
                const data = await http.HPost(CHECK_GROUP_STATUS, {order_num: newPayOrderIdRet.data})
                if (data.data.status === 1) {
                  Taro.hideLoading()
                  Taro.redirectTo({url: `/common/group/detail?orderNum=${newPayOrderIdRet.data}&category=${goodDetail.goods.category || 0}&itemId=${goodUuid}`})
                }
              }, 2500)
            } else {
              that.paySuccess(feeInfo.totalFee);
            }
          }
          return false
        }
        if (useAccountPay == 1) {
          //余额支付
          Taro.showModal({
            title: '提示',
            content: '您确定用余额支付吗?',
            cancelText: '取消',
            confirmText: '确定',
            success: async (res) => {
              if (res.confirm) {
                const result = await payment.orderPay(data)
                if (result) {
                  if (activityId) {
                    Taro.showLoading({title: '加载中...'})
                    setTimeout(async () => {
                      const data = await http.HPost(CHECK_GROUP_STATUS, {order_num: newPayOrderIdRet.data})
                      if (data.data.status === 1) {
                        Taro.hideLoading()
                        Taro.redirectTo({url: `/common/group/detail?orderNum=${newPayOrderIdRet.data}&category=${goodDetail.goods.category || 0}&itemId=${goodUuid}`})
                      }
                    }, 2500)
                  } else {
                    that.paySuccess(feeInfo.totalFee);
                  }
                }
              }
              that.setState({submiting: false, alldisable: false})
            }
          })
        } else if (useAccountPay == 2) {
          // 兑换码
          data['coupon_nums'] = JSON.stringify(this.state.flAry)
          const result = await newHttp.put(NEW_COUPON_PAY + data.newPayOrderId, data);
          if (result && result.status && result.status === 400) {
            this.setState({submiting: false})
            return Taro.showToast({title: result.data.message, icon: 'none'})
          }
          if (result && result.data.data) {
            this.setState({
              userBalance: false,
              welfare: false,
              submiting: false,
              alldisable: false,
              ticketSubMiting: true
            })
            const onlyTicketPay = this.state.onlyTicketPay === '1'
            if (onlyTicketPay) {
              const title = (onlyTicketPay ? '兑换成功' : '支付成功') + '!'
              Taro.showToast({title})
              setTimeout(() => {
                Taro.redirectTo({url: '/other/meal/index?params=' + (payData.phone || payData.idcard)})
              }, 1500)
              return false
            }
            that.paySuccess(-1);
          } else {
            try {
              const ary = result.data.message.split('_')
              const flAryIndex = flAry.indexOf(ary[0])
              this.setState({flAryIndex, flAryMsg: ary[1] || '请确认你的兑换码是正确的或未使用过', submiting: false, alldisable: false})
            } catch (e) {
              console.log(e)
            }
          }
        } else if (useAccountPay == 3) {
          //授信支付
          Taro.showModal({
            title: '提示',
            content: '您确定用授信支付吗?',
            cancelText: '取消',
            confirmText: '确定',
            success: async (res) => {
              if (res.confirm) {
                const result = await payment.orderPay(data)
                if (result) {
                  that.paySuccess(feeInfo.totalFee);
                }
              }
              that.setState({submiting: false, alldisable: false})
            }
          })
        } else if (useAccountPay == 4) {
          //授信支付
          Taro.showModal({
            title: '提示',
            content: '您确定用蝌蚪币支付吗?',
            cancelText: '取消',
            confirmText: '确定',
            success: async (res) => {
              if (res.confirm) {
                data.payClass = 14
                data.consume_fee = getFee['consume_fee']
                const result = await payment.orderPay(data)
                if (result) {
                  that.paySuccess(feeInfo.totalFee);
                }
              }
              that.setState({submiting: false, alldisable: false})
            }
          })
        } else {
          if (this.state.env == 'pc') {
            let api = ''
            if (process.env.TARO_ENV === 'h5' && data.useAccountPay !== 3) {
              api = H5_ORDER_PAY
            }
            if (process.env.TARO_ENV === 'h5') {
              data['paySource'] = 'gongzhonghao'
            }
            const pcQrode = await newHttp.catchGet(PC_QRCODE + this.state.newPayOrderIdRet.data, data)
            this.setState({pcqrcode: pcQrode, pcQrcodeShow: true})
            const time = setInterval(async () => {
              const status = await newHttp.catchGet(PC_ORDER_STATUS + this.state.newPayOrderIdRet.data)
              if (status.isPay) {
                clearInterval(time)
                this.setState({paySuccessShow: true});
              }
            }, 1000)
          } else {
            if (useAccountPay === 9999) {
              const {fromOrderNum} = Taro.getCurrentInstance().router.params
              that.setState({submiting: true, alldisable: true})
              const info = await http.postCar(CREATE_AND_PAY + fromOrderNum, data)
              if (info) {
                await payment.payment(info)
                that.paySuccess(feeInfo.totalFee)
              }
              that.setState({submiting: false, alldisable: false})
              return
            }
            this.setState({upFee: false})
            const result = await payment.orderPay(data)
            that.setState({submiting: false, alldisable: false})
            if (result) {
              if (activityId) {
                Taro.showLoading({title: '加载中...'})
                setTimeout(async () => {
                  const dataInfo = await http.HPost(CHECK_GROUP_STATUS, {order_num: newPayOrderIdRet.data})
                  if (dataInfo.data.status === 1) {
                    Taro.hideLoading()
                    Taro.redirectTo({url: `/common/group/detail?orderNum=${newPayOrderIdRet.data}&category=${goodDetail.goods.category || 0}&itemId=${goodUuid}`})
                  }
                }, 2500)
              } else {
                that.paySuccess(feeInfo.totalFee);
              }
            }
          }
        }
      } else {
        Taro.showToast({title: '下单失败[参数失败]', icon: 'none'})
        that.setState({submiting: false})
        return false
      }
    })

  }

  balancePay() {

  }

  makeFormData() {
    const {
      fromGoodDetail,
      contactData,
      linkDataList,
      feeInfo,
      getFee,
      userForm,
      goodDetail,
      buyDate,
      useIntegral,
      mealArrId,
      custom_item_key,
      payData
    } = this.state
    if (!goodDetail) return false
    const good = fromGoodDetail ? fromGoodDetail : goodDetail.goods
    const dateRange = JSON.stringify({start: buyDate.start, end: buyDate.end})
    const customString = JSON.stringify(this.makeCustomString())
    const userData = this.makeCustomString().arr[0]
    let formData: FormData = {
      hongbao: 0,
      linkman: '',
      phone: '',
      identity_num: '',
      remark: '',
      custom_item_detail: '',
      goods_id: 0,
      buy_amount: 0,
      hongbao_id: 0,
      message: '',
      reciver_province: '',
      reciver_city: '',
      reciver_area: '',
      useIntegral: false,
      jf: 0,
      goodsGroup: '',
      delivery_address: ''
    }
    if (good.is_custom_item === 0 && contactData[0].length !== 0) {
      formData = {
        message: userData.comments || '',
        hongbao: feeInfo.hbAmount,
        couponIsuseId: feeInfo.couponIsuseId || 0,
        linkman: linkDataList[0].name,
        phone: linkDataList[0].phone,
        identity_num: userData['idcard'] || '',
        defined_img: userData.upload_file ? userData.upload_file[0] : '',
        remark: payData.mark || '',
        face: userData.face || '',
        custom_item_detail: customString,
        custom_item_key: custom_item_key,
        goods_id: this.goodId,
        buy_amount: getFee.num,
        hongbao_id: getFee.hongbaoId,
        isSaveLinkInfo: 1,
        reciver_province: userData.province || '',
        reciver_city: userData.city || '',
        reciver_area: userData.region || '',
        delivery_address: userData.address || '',
        useIntegral,
        jf: useIntegral ? getFee.jf : 0,
        goodsGroup: this.state.goodsGroup.length > 0 ? JSON.stringify(this.state.goodsGroup) : '',
      }
    } else if (good.is_custom_item === 0 && contactData[0].length === 0) {
      formData = {
        message: payData.comments || '',
        couponIsuseId: feeInfo.couponIsuseId || 0,
        hongbao: feeInfo.hbAmount,
        linkman: payData.name,
        phone: payData.phone,
        identity_num: payData['idcard'] || '',
        defined_img: payData.upload_file ? payData.upload_file[0] : '',
        remark: payData.mark || '',
        face: payData.face || '',
        custom_item_detail: customString,
        custom_item_key: custom_item_key,
        goods_id: this.goodId,
        buy_amount: getFee.num,
        hongbao_id: getFee.hongbaoId,
        isSaveLinkInfo: 1,
        reciver_province: payData.province || '',
        reciver_city: payData.city || '',
        reciver_area: payData.region || '',
        delivery_address: payData.address || '',
        useIntegral,
        jf: useIntegral ? getFee.jf : 0,
        goodsGroup: this.state.goodsGroup.length > 0 ? JSON.stringify(this.state.goodsGroup) : '',
      }
    } else {
      formData = {
        message: userData.comments ? userData.comments : '',
        couponIsuseId: feeInfo.couponIsuseId || 0,
        hongbao: feeInfo.hbAmount,
        linkman: payData.name,
        phone: payData.phone,
        identity_num: userData['idcard'] || '',
        defined_img: userData.upload_file ? userData.upload_file[0] : '',
        remark: payData.mark || '',
        face: userData.face || '',
        custom_item_detail: customString,
        goods_id: this.goodId,
        buy_amount: getFee.num,
        hongbao_id: getFee.hongbaoId,
        reciver_province: userData.province || '',
        reciver_city: userData.city || '',
        reciver_area: userData.region || '',
        delivery_address: userData.address || '',
        useIntegral: useIntegral,
        jf: useIntegral ? getFee.jf : 0,
        goodsGroup: this.state.goodsGroup.length > 0 ? JSON.stringify(this.state.goodsGroup) : '',
      }
    }
    if (good.category == 3) {
      //集结地
      formData['assembling_place_list'] = JSON.stringify([{assembling_place: this.state.assembling_place}])
    }
    if (mealArrId) {
      formData['mealArrId'] = mealArrId
    }
    formData['referSellerId'] = Taro.getStorageSync('bindSellerId') || 0
    if (good.type === 1 && good.category !== 4) {
      if (good.category === 2) {
        formData.buy_date = buyDate.start
        formData.dateRange = dateRange
      } else {
        formData.buy_date = buyDate.start
      }
    }
    return formData
  }

  //组织图片数据上传
  uplodeImgAry() {
    const {userForm} = this.state
    const arr = userForm.map(item => {
      if (item.upload_file && item.upload_file.value) {
        return item.upload_file.value
      }
    })
    return arr
  }

  //组织下单用户信息数据上传
  makeCustomString() {
    const {contactData, goodDetail, payData, fromGoodDetail} = this.state
    const good = fromGoodDetail || this.state.goodDetail.goods
    const customDetail = {}
    customDetail['arr'] = []
    customDetail['custom_item_config'] = JSON.parse(good['custom_item_config'])
    if (goodDetail.goods.is_custom_item === 0 && contactData[0].length == 0) {
      customDetail['arr'].push(payData)
    } else {
      for (const k in contactData[0]) {
        if (contactData[0][k].value[0]['checked']) {
          customDetail['arr'].push(contactData[0][k].value[0])
        }
      }
      // 留言不能这样传，要和备注一致，现在处理的结果是：留言外层和联系人的同步信息，以外层留言为准
      if (payData && payData['comments']) {
        customDetail['arr'][0]['comments'] = payData['comments']
      } else {
        customDetail['arr'][0]['comments'] = ''
      }
      if (payData && payData['mark']) {
        customDetail['arr'][0]['mark'] = payData['mark']
      } else {
        customDetail['arr'][0]['mark'] = ''
      }
    }
    const customConfig = JSON.parse(good['custom_item_config'])
    for (const item in customConfig) {
      for (const k in customDetail['arr']) {
        // 修改传值，需要什么传什么值，如：未开启图片，但是用户之前的信息里有图片，就不要再传了
        if (!customConfig[item]) {
          customDetail['arr'][k][item] = ''
        }
        // 会有自定义信息的情况，即联系人信息中有该字段，但必填信息中没有，此时要删除该字段 field_
        for (const key in customDetail['arr'][k]) {
          if (key.indexOf('field_') > -1 && (customConfig[key] == "undefined" || customConfig[key] == null)) {
            customDetail['arr'][k][key] = ''
          }
        }
        if (!customConfig['address']) {
          customDetail['arr'][k]['province'] = ''
          customDetail['arr'][k]['city'] = ''
          customDetail['arr'][k]['region'] = ''
        }
      }
    }
    return customDetail
  }


  async showCalendar() {
    if (this.state.alldisable) {
      return false;
    }
    this.setState({showCalendar: true})
  }

  //切换日期
  changeDate(value, status) {
    if (status !== 1) {
      Taro.showToast({title: `已售罄`, icon: 'none',})
      return
    }
    this.setState({showCalendar: false, buyDate: {start: value || ''}}, async () => {
      const feeInfo = await this.getFee()
      if (feeInfo) {
        this.setState({feeInfo, fristShow: false, defaultDate: true})
      } else {
        this.setState({showCalendar: true, defaultDate: true})
      }
    })
  }

  calendarSelect(value: { start: string; end: string; type: string; single: string; range: string[] }) {
    const {threeDate} = this.state
    if (value.type === 'range') {
      this.setState({showCalendar: false, buyDate: {start: value.start || '', end: value.end}}, async () => {
        const feeInfo = await this.getFee()
        if (feeInfo) {
          this.setState({feeInfo, fristShow: false})
        } else {
          this.setState({showCalendar: true})
        }
      })
    } else {
      this.setState({showCalendar: false, buyDate: {start: value.single || ''}}, async () => {
        const feeInfo = await this.getFee()
        if (feeInfo) {
          this.setState({feeInfo, fristShow: false})
        } else {
          this.setState({showCalendar: true})
        }
      })
    }
    const day = new Date(value.single).getDay()
    const _threeDate = this.state.threeDate
    const dateAry = value.single.split('-')
    if (value.single != _threeDate[0].date && value.single != _threeDate[1].date) {
      _threeDate[2].showDate = dateAry[1] + '-' + dateAry[2],
        _threeDate[2].date = value.single
      _threeDate[2].week_str = this.state.week[day]
      _threeDate[2].status = 1
    }
    this.setState({threeDate: _threeDate, defaultDate: true})
    // const day = new Date(value.single).getDay()
    // const dateAry = value.single.split('-')
    // if (value.single != this.GetDateStr(0, threeDate[0].subDate) && value.single != this.GetDateStr(1, threeDate[1].subDate) && value.single != this.GetDateStr(2, threeDate[2].subDate)) {
    //   threeDate[2] = {
    //     showDate: dateAry[1] + '-' + dateAry[2],
    //     subDate: value.single,
    //     name: this.state.week[day]
    //   }
    // }
  }

  saveLinkInfo() {
    if (this.state.alldisable) {
      return
    }
    this.setState({
      isSaveLinkInfo: !this.state.isSaveLinkInfo
    })
  }

  async delLinkInfo(id, index) {
    if (this.state.alldisable) {
      return
    }
    Taro.showModal({
      title: '提示',
      content: '是否删除该常用联系人',
      success: async res => {
        if (res.confirm) {
          const list = this.state.lineList
          const r = await http.postCondition(DEL_LINK_INFO, {id})
          if (r.isOk) {
            list.splice(index, 1);
            this.setState({
              listInfo: list
            }, () => {
              Taro.showToast({
                title: '已删除',
                icon: 'none'
              })
            })

          } else {
            Taro.showToast({
              title: '删除失败',
              icon: 'none'
            })
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  }

  checkLineInfo(id, e) {
    if (this.state.alldisable) {
      return
    }
    e.stopPropagation()
    const {lineList} = this.state
    if (id == this.state.checkId) {
      this.setState({
        checkId: 0
      })
    } else {
      let formlist
      const userForm = this.state.userForm
      lineList.map(item => {
        if (item.id == id) {
          formlist = item.config[0]
          for (const key in userForm[0]) {
            if (key == 'custom') {
              userForm[0][key].map((items, i) => {
                items.value = formlist[items.key]
              })
            } else if (key == 'region') {
              userForm[0].region.value = [formlist.province, formlist.city, formlist.region]
            } else if (key == 'mark') {
              userForm[0][key].value = formlist.remark ? formlist.remark : ''
            } else if (key == 'idcard') {
              userForm[0][key].value = formlist.idcard ? formlist.idcard : ''
            } else if (key == 'upload_file') {
              userForm[0][key].value = formlist.upload_file ? formlist.upload_file : []
            } else {
              userForm[0][key].value = formlist[key] ? formlist[key] : ''
            }
          }
          this.setState({
            userForm,
            checkId: id
          })
        }
      })

    }

  }

  openTip() {
    const opentips = this.state.opentips
    this.setState({opentips: !opentips})
  }

  openTips(goodsGroup, index) {
    goodsGroup[index]['opentips'] = !goodsGroup[index]['opentips']
    this.setState({goodsGroup})
  }

  assembling(val) {
    val.detail.value
    const {goodDetail} = this.state
    this.setState({
      assembling_place: goodDetail.goods.assembling_place_list[val.detail.value].assembling_place
    })

  }

  async syncUpload(localIds, group, api) {
    const that = this
    let {contactData, idcardTime} = this.state
    for (let i = 0; i < localIds.length; i++) {
      h5Wx.wxuploadImage(localIds[i], async res => {
        if (group == 1) {
          const dataRet = await newHttp.catchGet(materialMedia + res, {media_id: res})
          if (dataRet) {
            if (dataRet) {
              contactData['upload_file'].push(dataRet)
              that.setState({contactData, idcardTime})
            }
          }
          if (i === localIds.length - 1) {
            Taro.hideToast();
          }
        } else {
          const dataRet = await newHttp.catchPost(api, {media_id: res}, true)
          Taro.hideToast();
          const data = dataRet;
          if (dataRet.status == 400) {
            Taro.showToast({
              title: data.message,
              icon: 'none'
            })
            return
          }
          if (group === 0) {
            if (data && data.idcard) {
              contactData.idcard = data.idcard
              idcardTime++
            }
          }
          if (group === 1) {
            if (data.imageUrl) {
              contactData['upload_file'].push(data.imageUrl)
            }
          }
          if (group === 2) {
            if (data.domain && data.url) {
              contactData['face'] = data.domain + data.url
            }
          }
          that.setState({contactData, idcardTime})
        }
      })
    }
  }

  uplodeImg(group = 0) {
    const that = this
    const count = group === 1 ? 9 : 1
    let {contactData, idcardTime, payData} = this.state
    if (group === 0) {
      contactData['idcard'] = ''
    }
    this.setState({contactData})
    const apiList = [OCR, UPLODE_FALE, FACE]
    const api = BASE_URL + apiList[group]
    if (process.env.TARO_ENV === 'h5') {
      if (process.env.P_ENV === 'lx') {
        lxH5Wx.chooseImage(async (files, length) => {
          if (group === 1) { // 图片
            lxH5Wx.uploadFile(files, length, (url) => {
              if (!contactData.upload_file) {
                contactData['upload_file'] = []
              }
              if (!payData.upload_file) {
                payData['upload_file'] = []
              }
              contactData['upload_file'].push(url)
              payData['upload_file'].push(url)
              that.setState({contactData, payData})
            })
          } else if (group === 2) { // 人脸
            lxH5Wx.uploadFace(files, length, (url) => {
              contactData['face'] = url
              payData['face'] = url
              that.setState({contactData, payData})
            })
          } else if (group === 0) {
            lxH5Wx.uploadOcr(files, length, (data) => {
              contactData.idcard = data.idcard
              payData.idcard = data.idcard
              that.setState({contactData, payData})
            })
          }
        }, group === 1 ? 2 : 1)
      } else {
        h5Wx.chooseImage(count, async ret => {
          Taro.showToast({
            title: group === 0 ? '正在识别...' : '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          that.syncUpload(ret, group, api)
        }, 'big')
      }
    } else {
      Taro.chooseImage({
        count,  //最多可以选择的图片总数
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths;
          //启动上传等待中...
          Taro.showToast({
            title: group === 2 ? '正在识别...' : '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          let uploadImgCount = 0;
          for (let i = 0, h = tempFilePaths.length; i < h; i++) {
            Taro.uploadFile({
              url: api,
              filePath: tempFilePaths[i],
              name: group === 2 ? 'face' : 'file',
              formData: {
                'imgIndex': i
              },
              header: http.getHeader(),
              success: function (res) {
                uploadImgCount++;
                const data = JSON.parse(res.data);
                if (res.statusCode == 400) {
                  Taro.showToast({
                    title: data.message,
                    icon: 'none'
                  })
                  return
                }
                if (group === 0) {
                  if (data.data && data.data.idcard) {
                    contactData.idcard = data.data.idcard
                    idcardTime++
                  }
                }
                if (group === 1) {
                  if (data.imageUrl) {
                    contactData['upload_file'].push(data.imageUrl)
                  }
                }
                if (group === 2) {
                  if (data.data.domain && data.data.url) {
                    contactData['face'] = data.data.domain + data.data.url
                  }
                }

                //如果是最后一张,则隐藏等待中
                if (uploadImgCount == tempFilePaths.length) {
                  that.setState({contactData, idcardTime})
                  Taro.hideToast();
                }
              },
              fail: function (res) {
                Taro.hideToast();
                Taro.showModal({
                  title: '错误提示',
                  content: '上传图片失败',
                  showCancel: false,
                  success: function (res) {
                  }
                })
              }
            });
          }
        }
      })
    }
  }

  delUplodeImg(index) {
    const {payData} = this.state
    if (index == 2) {
      payData['face'] = ''
    } else {
      payData['upload_file'] = []
    }
    this.setState({payData})
  }

  lookCalendar() {
    this.setState({
      look: true
    })
  }

  calendarClose() {
    this.setState({
      look: false
    })
  }

  toggleWelfare() {
    this.setState({welfare: !this.state.welfare})
  }

  flInput(index, val) {
    const {flAry} = this.state
    let flAryIndex = this.state.flAryIndex
    flAry[index] = val.detail.value
    if (flAryIndex == index) {
      flAryIndex = -1
    }
    this.setState({flAry, flAryIndex})
  }

  //选择红包
  checkRedbag() {
    const {alldisable, feeInfo} = this.state
    if (!alldisable) {
      this.setState({upFee: true})
      Taro.navigateTo({
        url: "/main/my/redbag/list?select=" + feeInfo.maxAmount
      })
    }
  }

  getCanUseRedBag() {
    if (process.env.P_ENV === 'lx') {
      return process.env.TARO_ENV !== 'h5'
    }
    return true
  }

  //去充值
  chongzhi() {
    this.setState({upFee: true})
    Taro.navigateTo({
      url: '/distributor/wallet/recharge'
    })
  }

  // 获取近三天日期
  getThreeDate(isToast) {
    const that = this
    const {buyDate, goodDetail} = this.state
    const dayEnd = goodDetail.goods.booking_day_end
    const date: any = []
    let str1: string;
    let str2: string;
    const today = new Date();
    const week = ['周天', '周一', '周二', '周三', '周四', '周五', '周六']
    const dateName = ['今天', '明天']
    for (let i = 0 + dayEnd; i < 3 + dayEnd; i++) {
      str1 = that.GetDateStr(i, false)
      str2 = that.GetDateStr(i, true)
      const dateArr = str2.split('-')
      date.push({
        showDate: str1,
        subDate: str2,
        name: dayEnd > 0 ? this.oneDay(dateArr[0], dateArr[1], dateArr[2]) : dateName[i]
      })
      // dateName[i]
    }
    const dateArrThree = date[2].subDate.split('-')
    date[2].name = dayEnd > 0 ? this.oneDay(dateArrThree[0], dateArrThree[1], dateArrThree[2]) : week[today.getDay() + 2 >= 7 ? today.getDay() + 2 - 7 : today.getDay() + 2]

    this.setState({threeDate: date})
  }

  oneDay(y, m, d) {
    const myDate = new Date();
    myDate.setFullYear(y, m - 1, d);
    const week = myDate.getDay()
    switch (week) {
      case 0:
        return '周日';
      case 1:
        return '周一';
      case 2:
        return '周二';
      case 3:
        return '周三';
      case 4:
        return '周四';
      case 5:
        return '周五';
      case 6:
        return '周六';
    }
  }

  //获取日期
  GetDateStr(AddDayCount, isY = true, date = this.state.buyDate.start) {
    const dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
    const y = dd.getFullYear();
    const m = dd.getMonth() + 1;//获取当前月份的日期
    const d = dd.getDate();
    if (isY) return y + "-" + (m < 10 ? '0' + m : m) + "-" + (d < 10 ? '0' + d : d);
    else return (m < 10 ? '0' + m : m) + "-" + (d < 10 ? '0' + d : d);
  }

  // 联系人姓名电话
  personInput(name, value) {
    this.state.payData[name] = value
    if (!value) {
      this.setState({payData: this.state.payData})
    }
  }

  swapArr(arr, index1, index2) {
    arr[index1].unshift(arr[index1][index2])
    arr[index1][0]['value'][0]['num'] = arr[index1][1]['value'][0]['num']
    arr[index1].splice(index2 + 1, 1)
    return arr;
  }

  async getDaysBetween(dateString1, dateString2) {
    const startDate = Date.parse(dateString1);
    const endDate = Date.parse(dateString2);
    if (startDate > endDate) {
      return 0;
    }
    if (startDate == endDate) {
      return 1;
    }
    return (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
  }

  getSelectorQuery() {
    // if (this.state.itemH != 0) return
    let itemH = 0
    Taro.createSelectorQuery().selectAll('.meal_item').boundingClientRect(function (rects) {
      rects.forEach(function (rect, index) {
        if (index > 2) return false
        itemH += rect.height
      })
    }).exec(() => {
      this.setState({itemH})
    })
  }

  async openCoupon() {
    const offOpenCoupon = this.state.offOpenCoupon
    if (offOpenCoupon) {
      const feeInfo = await this.getFee()
      this.setState({
        feeInfo
      })
    }
    this.setState({
      offOpenCoupon: !offOpenCoupon
    })
  }

  checkMeal(index) {
    const {feeInfo} = this.state
    if (index > -1) {
      feeInfo.couponIsuseId = feeInfo.coupon_list[index].id
      this.setState({
        notUse: false,
        couponMoney: feeInfo.coupon_list[index].coupon_discounts_money,
        couponMoneyName: feeInfo.coupon_list[index].amount_limit_str,
        feeInfo
      })
    } else {
      feeInfo.couponIsuseId = 0
      this.setState({notUse: true, couponMoney: 0, couponMoneyName: '', feeInfo})
    }
    this.openCoupon()
  }

  agree(val) {
    this.setState({
      agree: !val
    })
  }

  paySuccess(id) {
    const env = Taro.getCurrentInstance().router.params.env;
    if (env == 'pc') {
      this.setState({
        paySuccessShow: true
      });
    } else {
      Taro.redirectTo({url: '/main/order/success?pay=' + id});
    }
  }

  handleCityData = key => {
    const {addressData} = this.state
    // 处理数据。
    const provinceList = []; // 省
    const cityList = []; // 市
    const areaList = []; // 区
    for (let i = 0; i < addressData.length; i++) {
      // 获取省
      const province = addressData[i];
      provinceList.push(province.name);
    }
    if (addressData[key[0]].areaList && addressData[key[0]].areaList.length > 0) {
      for (let i = 0; i < addressData[key[0]].areaList.length; i++) {
        // 获取对应省下面的市
        const city = addressData[key[0]].areaList[i];
        cityList.push(city.name);
      }
    }
    for (
      let i = 0;
      i < addressData[key[0]].areaList[key[1]].areaList.length;
      i++
    ) {
      // 获取市下面对应区
      const country = addressData[key[0]].areaList[key[1]].areaList[i].name;
      areaList.push(country);
    }
    // }
    const newRange = [];
    newRange.push(provinceList);
    newRange.push(cityList);
    newRange.push(areaList);
    this.setState({
      rangeData: newRange, // 省市区所有的数据
      rangeKey: key // key是多列选择器需要展示的下标，因为是初始化，所以我们传入[0,0,0]
    });
  };
  onChange = e => {
    const {value} = e.detail;
    this.getAddressName(value);
  };
  getAddressName = value => {
    // 这里是转化用户选择的地址数据
    const {payData, addressData} = this.state
    const formData = {
      province: "",
      city: "",
      region: ""
    };
    if (addressData[value[0]]) {
      formData.province = addressData[value[0]].name; // 省名称
      if (
        addressData[value[0]].areaList &&
        addressData[value[0]].areaList[value[1]]
      ) {
        formData.city = addressData[value[0]].areaList[value[1]].name;
        if (
          addressData[value[0]].areaList[value[1]].areaList &&
          addressData[value[0]].areaList[value[1]].areaList[value[2]]
        ) {
          formData.region =
            addressData[value[0]].areaList[value[1]].areaList[
              value[2]
              ].name;
        }
      }
    }
    payData['province'] = formData.province
    payData['city'] = formData.city
    payData['region'] = formData.region
    this.setState({
      payData, regions: [formData.province + ',' + formData.city + "," + formData.region]
    });
  };
  onColumnChange = e => {
    const {rangeKey} = this.state;
    const changeColumn = e.detail;
    const {column, value} = changeColumn;
    switch (column) { // 根据改变不同的列，来显示不同的数据
      case 0:
        this.handleCityData([value, 0, 0]);
        break;
      case 1:
        this.handleCityData([rangeKey[0], value, 0]);
        break;
      case 2:
        this.handleCityData([rangeKey[0], rangeKey[1], value]);
        break;
    }
  };

  lookDetail() {
    this.setState({detailShow: !this.state.detailShow})
  }

  render() {
    const dataColor = Taro.getStorageSync('colorData');
    const {
      bottomView,
      linkShow,
      openKD,
      openTraveler,
      detailShow,
      activityId,
      rangeData,
      regions,
      rangeKey,
      fromGoodDetail,
      agree,
      paySuccessShow,
      pcQrcodeShow,
      pcqrcode,
      fieldCustom,
      region,
      custom_item_config,
      linkDataList,
      indextime,
      days,
      itemH,
      notUse,
      offOpenCoupon,
      couponMoney,
      couponMoneyName,
      showLoading,
      showLoadingLink,
      notice,
      floatLayout,
      payData,
      lookMoreShow,
      threeDate,
      contactData,
      idcardDelIndex,
      layoutIndex,
      floatLayoutIdcard,
      isiPhonex,
      userOk,
      meals,
      flAry,
      flAryIndex,
      flAryMsg,
      useIntegral,
      redbag,
      upCount,
      booking_day_end,
      booking_time_end,
      goodDetail,
      feeInfo,
      getFee,
      step,
      showCalendar,
      calendarInfo,
      assembling_place,
      opentips,
      alldisable,
      buyDate,
      ticketSubMiting,
      submiting,
      onlyTicketPay,
      platformSet,
      fristShow,
      userBalance,
      zero,
      look,
      isLeader,
      welfare,
      defaultDate,
      isDaypartingAppointment,
      pageType
    } = this.state
    const userFormTemplateArr = this.state.userFormTemplate && JSON.parse(this.state.userFormTemplate)
    const discount: number = feeInfo.hbAmount + feeInfo.integralDeduction
    const _env = Taro.getCurrentInstance().router.params.env;
    // 渲染最大可用积分的展示
    const renderCanUseMaxJF = () => {
      // 自动使用积分
      if (goodDetail.goods.is_auto_use_integral == 1) {
        return getFee.jf;
      }else { // 不自动使用
        if(this.state.getFee.jf == 0 && feeInfo.maxJf > 0) {
          // 初始化为最大积分
          return feeInfo.maxJf;
        }else {
          if(process.env.P_ENV === 'kontai') {
            // 天逸游展示的最大可用积分, 随改变而改变
            return getFee.jf;
          }else {
            // 其它平台展示的最大可用积分固定不变
            return feeInfo.maxJf;
          }
        }
      }
    }

    return (
      <View className='root confirm-root confirm-person-style'>
        <GzhAuth />
        {goodDetail && goodDetail.goods && <Block>
          <Skeleton title row={6} loading={showLoading}>
            <View>
              <View className='good-info'>
                <View className='title'>{goodDetail.goods.product_name}</View>
                {goodDetail && (goodDetail.goods.type === 1 || goodDetail.goods.type === 2) && goodDetail.goods.category !== 4 &&
                <Block>
                  {goodDetail.goods.category === 1 ? <Block>
                      {(goodDetail.goods.effective_end_show || goodDetail.goods.effective_begin_show || goodDetail.goods.valid_date_type == 5) &&
                      <Block>
                        <View className='item'>
                          <View className='text'><AtIcon className='dateIcon' prefixClass='car' value='iconshijian'
                            size='14'
                            color='#333'
                          />
                            指定有效期内可用
                            {goodDetail.goods.valid_date_type == 5 &&
                            <View className='select-btn' onClick={this.lookCalendar.bind(this)}>查看</View>}
                          </View>
                          {(goodDetail.goods.effective_end_show || goodDetail.goods.effective_begin_show) &&
                          <View className='text'><AtIcon customStyle='margin-right:4px' prefixClass='car' value='iconrili'
                            size='12' color='#333'
                          /><Text
                            decode
                          >{goodDetail.goods.effective_begin_show}{goodDetail.goods.effective_end_show}</Text></View>}
                        </View>
                        <AtFloatLayout isOpened={look} title='有效期' onClose={this.calendarClose.bind(this)}>
                          <AtCalendar validDates={goodDetail.goods.rangeCalendar} />
                        </AtFloatLayout>
                      </Block>
                      }
                    </Block>
                    :
                    <Block>
                      {(goodDetail.goods.category && goodDetail.goods.category !== 2 && goodDetail.goods.category != 5) ?
                        <Block>
                        </Block>
                        :
                        <Block>
                          {goodDetail.goods.open_meal == 1 ? <Block>
                              {(goodDetail.goods.meal_valid_date_set == 1) && <View className='item'>
                                <View className='text'><AtIcon className='dateIcon' prefixClass='car' value='iconshijian'
                                  size='14' color='#333'
                                />
                                  指定日期有效期内可用
                                </View>
                                <View className='text'><AtIcon customStyle='margin-right:4px' prefixClass='car'
                                  value='iconrili'
                                  size='12' color='#333'
                                />
                                  <Text>{goodDetail.goods.effective_begin_show}{goodDetail.goods.effective_end_show}</Text>
                                </View>
                              </View>}
                            </Block>
                            :
                            <Block>
                              {(goodDetail.goods.effective_begin_show != '' || goodDetail.goods.meal_valid_date_set !== 1) &&
                              <View className='item'>
                                <View className='text'><AtIcon className='dateIcon' prefixClass='car'
                                  value='iconshijian'
                                  size='14' color='#333'
                                />
                                  指定日期有效期内可用
                                </View>
                                {goodDetail.goods.category !== 2 &&
                                <View className='text'><AtIcon customStyle='margin-right:4px' prefixClass='car'
                                  value='iconrili' size='12' color='#333'
                                />
                                  <Text>{goodDetail.goods.effective_begin_show}{goodDetail.goods.effective_end_show}</Text>
                                </View>}
                              </View>}
                            </Block>
                          }
                        </Block>
                      }
                    </Block>
                  }
                </Block>}
                {goodDetail && goodDetail.goods.category == 3 && goodDetail.goods.assembling_place_list && goodDetail.goods.assembling_place_list.length > 0 &&
                <View className='page-section'>
                  <Picker mode='selector' range={goodDetail.goods.assembling_place_list} rangeKey='assembling_place'
                    onChange={this.assembling.bind(this)}
                  >
                    <AtList hasBorder={false}>
                      <AtListItem
                        extraText='更改'
                        hasBorder={false}
                        title={assembling_place ? `出发地: ${assembling_place}` : '出发地: 请选择集合地点'}
                      />
                    </AtList>
                  </Picker>
                </View>}
                {goodDetail && !!goodDetail.goods.category && goodDetail.goods.category != 5 && goodDetail.goods.category != 2 && goodDetail.goods.is_open != 0 &&
                <View>
                  <View
                    className='use_date_title'
                  >{goodDetail.goods.category == 1 || goodDetail.goods.category == 3 ? '出行日期' : '使用日期'} </View>
                  {threeDate && <View className='use_date_box'>
                    {threeDate && threeDate.map((item, index) =>
                      <View onClick={this.changeDate.bind(this, item.date, item.status)} key={index}
                        style={`background: ${!defaultDate ? '' : buyDate.start.includes(item.date) && process.env.mainColor};`}
                        className={`user-date-item ${!defaultDate ? '' : buyDate.start.includes(item.date) && 'active-date'} ${fromGoodDetail ? 'disabled-from' : ''}`}
                      >
                        <View>{item.week_str}</View>
                        <View className='use_showdate'>{item.showDate}
                          <View> {item.status != 1 ? '(售罄)' : ''}</View></View>
                      </View>
                    )}
                    {calendarInfo.length > 0 ?
                      <View onClick={this.showCalendar.bind(this)} className=' user-date-item more_date'>
                        <View className='lt'>
                          <View>更多</View>
                          <View>日期</View>
                        </View>
                        <View><AtIcon value='chevron-right' size='18' color='#000' /></View>
                      </View>
                      :
                      <View className='more_date'></View>
                    }
                  </View>}
                </View>}
                {goodDetail && !!goodDetail.goods.category && goodDetail.goods.category === 2 && <View className='item'>
                  <View className='text'>
                    <AtIcon customStyle='margin-right:4px' prefixClass='car' value='iconrili' size='12'
                      color='#333'
                    />
                    {(goodDetail.goods.sale_style === 1) ? <Block>
                      {(goodDetail.goods.effective_end_show || goodDetail.goods.effective_begin_show) &&
                      <View className='text' style='display: inline;'><Text
                        decode
                      >{goodDetail.goods.effective_begin_show}{goodDetail.goods.effective_end_show}</Text></View>
                      }
                    </Block> : <Text decode>
                      {buyDate.start} - {buyDate.end} 住{days}晚
                    </Text>}
                  </View>
                </View>}

                <Skeleton title row={6} rowHeight={30} loading={showLoadingLink}>
                  <Block>
                    {(meals.length > 0) &&
                    <View className='meal_box'>
                      <Text className='meal_title'>套餐包含</Text>
                      <View style={itemH ? {height: itemH + 'px'} : {}}
                        className={`meal_list ${lookMoreShow ? 'more_show' : ''} ${itemH != 0 ? 'meal_h' : ''} `}
                      >
                        {meals.map((item, index) =>
                          <View className='meal_item' key={index}>
                            <View className='top'>
                              <Text className='title'>{item.productName}</Text>
                              <Text className='price'>x{item.amount}</Text>
                            </View>
                            {goodDetail.goods.meal_valid_date_set !== 1 &&
                            <View className='meal_date'>{item.validDate}</View>}
                          </View>
                        )}
                      </View>
                      {meals.length > 3 &&
                      <View onClick={() => (this.setState({lookMoreShow: !this.state.lookMoreShow}))}
                        className='look_more flex_center_center'
                      >
                        {!lookMoreShow ? '查看更多' : '收起更多'}
                        {!lookMoreShow && <AtIcon value='chevron-down' size='14' color='#B6B6B7' />}
                        {lookMoreShow && <AtIcon value='chevron-up' size='14' color='#B6B6B7' />}
                      </View>}
                    </View>}
                  </Block>
                </Skeleton>

                <View className='item num'>
                  {goodDetail.goods && (goodDetail.goods.category !== 0 && goodDetail.goods.category !== null) &&
                  <Block>
                    <View className='title'>
                      {goodDetail.goods.category != 5 ? <View className='lt'>{goodDetail.goods.name}</View> :
                        <View></View>}
                      {feeInfo.goodsPrice > 0 && !fromGoodDetail && <View className='rt'>
                        <Text style={`color: ${dataColor.priceColor}`} className='icon_ren'>¥</Text>
                        <Text style={`color: ${dataColor.priceColor}`} className='price'>{feeInfo.goodsPrice}</Text>
                      </View>}
                    </View>
                    <View className='label'>
                      {goodDetail.goods.bookingEndShow && <Text className='label_item'>
                        {goodDetail.goods.bookingEndShow}<Text className='separate'>|</Text>
                      </Text>}
                      {goodDetail.goods.notice && <View className='buy_notes' onClick={() => {
                        this.setState({notice: goodDetail.goods.notice}, () => {
                          if (goodDetail.goods.notice) {
                            this.setState({floatLayout: true})
                          }
                        })
                      }}
                      > 购买须知 <AtIcon value='chevron-right' size='14' color='#B6B6B7' /></View>}
                    </View>
                  </Block>}
                  <View className='input-number'>
                    {(goodDetail.goods.category == 5 || goodDetail.goods.category == 1 || !goodDetail.goods.category) ?
                      <View className='buy_num'>购买数量</View> : <View />}
                    {getFee.num &&
                    <NumberInput onBlur={this.iosScroll.bind(this)} val={getFee.num} index={indextime} step={1}
                      min={feeInfo.buy_num_min < 2 ? 1 : feeInfo.buy_num_min}
                      max={feeInfo.buy_num_max} disabled={fromGoodDetail || alldisable}
                      thisChange={this.inputNumber.bind(this)}
                    />}
                  </View>
                  {goodDetail.goods && goodDetail.goods.tips_msg && pageType !== "limitedSeckill" && <View className='tips_msg'>
                    {goodDetail.goods.tips_msg.length > 0 && goodDetail.goods.tips_msg.map((items, i) =>
                      <Block key={i}>
                        {i > 0 && opentips
                          ?
                          <View className='tips_msg_item'>
                            {items}
                          </View>
                          :
                          <Block>
                            {i == 0 && <View className='tips_msg_item' key={i} onClick={this.openTip.bind(this)}>
                              <AtIcon customStyle='position:relative;top:2px;' value='chevron-down' size='8'
                                color='#fff'
                              />
                              {items}
                            </View>}
                          </Block>}
                      </Block>
                    )}
                  </View>}
                </View>
              </View>
            </View>
          </Skeleton>
          <Skeleton title row={3} rowHeight={120} loading={showLoadingLink}>
            <View className='person'>
              {openTraveler && (contactData && contactData[0] && contactData[0].length > 0 || goodDetail && goodDetail.goods && goodDetail.goods.is_custom_item > 0) &&
              <Block>
                <View className='idcard_box'>
                  <View className='name_info'>
                    {goodDetail && goodDetail.goods && goodDetail.goods.is_custom_item === 0 ?
                      <View className='name_info_item'><Text className='name_info_tips'>仅需添加 1 位联系人信息</Text></View>
                      :
                      <View className='name_info_item'>出行人 <Text className='name_info_tips'>需添加 <Text
                        className='code'
                      >{goodDetail && goodDetail.goods && goodDetail.goods.is_custom_item == 0 ? 1 : getFee.num}</Text> 位联系人信息，用于验证身份</Text></View>}
                  </View>
                  <Skeleton title row={2} rowHeight={40} loading={showLoadingLink}>
                    <View className='idCard_label'>
                      {(contactData && contactData[0] && contactData[0].length > 0) && <Block>
                        {contactData[0].map((list, idx) =>
                          <Block key={idx}>
                            {idx < 3 && <View
                              onClick={this.selectContact.bind(this, 0, idx, goodDetail.goods.is_custom_item == 0 ? 1 : getFee.num)}
                              className={`flex_center_center ${list.value[0].checked ? 'active' : ''} `}
                              style={`border: 1px solid ${process.env.mainColor};color: ${process.env.mainColor}`}
                            >
                              {list.value[0].name}
                              {list.value[0].checked &&
                              <View className='checked' style={`background: ${process.env.mainColor}`}>
                                <AtIcon value='check' size='8' color='#fff' />
                              </View>}
                            </View>}</Block>)}
                      </Block>}
                      {(contactData && contactData.length > 0 && contactData[0] && contactData[0].length > 0) && contactData[0].length <= 3 &&
                      <View onClick={this.jump.bind(this, 0, goodDetail.goods.id, goodDetail.goods.custom_item_config)}
                        className='flex_center_center add' style={`background: ${process.env.mainColor}`}
                      >
                        <AtIcon customStyle='margin-right:4px' value='add-circle' size='14' color='#fff' />
                        添加
                      </View>}
                      {(contactData && contactData.length > 0 && contactData[0] && contactData[0].length > 0) && contactData[0].length > 3 &&
                      <View onClick={() => this.setState({floatLayoutIdcard: true, layoutIndex: 0})}
                        className='flex_center_center add' style={`background-color: ${process.env.mainColor}`}
                      >
                        <AtIcon customStyle='margin-right:4px' value='add-circle' size='14' color='#fff' />
                        更多
                      </View>}
                      {!(contactData && contactData.length > 0 && contactData[0] && contactData[0].length > 0) &&
                      <View onClick={this.jump.bind(this, 0, goodDetail.goods.id, goodDetail.goods.custom_item_config)}
                        className='flex_center_center add' style={`background: ${process.env.mainColor}`}
                      >
                        <AtIcon customStyle='margin-right:4px' value='add-circle' size='14' color='#fff' />
                        添加
                      </View>}
                    </View>
                  </Skeleton>
                  <Skeleton title row={1} rowHeight={60} loading={showLoadingLink}>
                    {linkDataList && linkDataList.map((list, idx) =>
                      <Block key={idx}>
                        <View className='idCard_list'>
                          <View className='subtract_circle'>
                            {goodDetail && goodDetail.goods && goodDetail.goods.is_custom_item > 0 &&
                            <View>游客{idx + 1}</View>}
                            {list &&
                            <AtIcon
                              onClick={this.delSelectContact.bind(this, 0, idx, getFee.num, list.phone, list.name)}
                              value='close-circle' size='20' color='#B9B8BE'
                            />}
                          </View>
                          <View className='idCard_list_item'>
                            {list == '' ?
                              <View
                                onClick={this.jump.bind(this, 0, goodDetail.goods.id, goodDetail.goods.custom_item_config)}
                                className='tips-one'
                              >
                                点击补全游客信息
                              </View>
                              :
                              <Block>
                                <View className='info-list'>
                                  <View className='info-list-view'>{list.name}</View>
                                  <View className='info-list-view'>手机号 {list.phone}</View>
                                  {custom_item_config.idcard && list.idcard &&
                                  <View className='idcard info-list-view'>身份证 {list.idcard}</View>}
                                </View>
                                {list.isInfo && <View
                                  onClick={this.edit.bind(this, 0, idx, fromGoodDetail ? fromGoodDetail.id : goodDetail.goods.id, fromGoodDetail ? fromGoodDetail.custom_item_config : goodDetail.goods.custom_item_config, list.phone, list.name)}
                                  className='tips-two'
                                >
                                  缺少信息，点击补全
                                </View>}
                              </Block>
                            }
                          </View>

                          <View className='rt-box'>
                            {idcardDelIndex == 0 + '-' + idx &&
                            <View onClick={this.delSelectContact.bind(this, 0, idx, getFee.num)}
                              className='del-btn'
                            >删除</View>}
                            {(list && list != '') ?
                              <View className='chevron_right' style={`color: ${process.env.mainColor}`}
                                onClick={this.edit.bind(this, 0, idx, fromGoodDetail ? fromGoodDetail.id : goodDetail.goods.id, fromGoodDetail ? fromGoodDetail.custom_item_config : goodDetail.goods.custom_item_config, list.phone, list.name)}
                              >
                                编辑
                              </View>
                              :
                              <View className='chevron_right' style={`color: ${process.env.mainColor}`}
                                onClick={this.jump.bind(this, 0, fromGoodDetail ? fromGoodDetail.id : goodDetail.goods.id, fromGoodDetail ? fromGoodDetail.custom_item_config : goodDetail.goods.custom_item_config,)}
                              >
                                编辑
                              </View>
                            }
                          </View>
                        </View>
                      </Block>)}
                  </Skeleton>
                </View>
              </Block>}

              {/*联系人*/}
              {openTraveler && goodDetail && (goodDetail && goodDetail.goods && goodDetail.goods.is_custom_item === 0 &&
                ((contactData && contactData[0] && contactData[0].length == 0) || linkShow)) &&
              <Block>
                <View className='contact_box'>
                  <View className='title'>
                    <View className='font_size_28'>联系人</View>
                    <View className='font_size_24'>请添加联系人用于接收出票信息</View>
                  </View>
                  <AtForm className='person'>
                    {custom_item_config.name && <AtInput className='require' name='linkman' value={payData.name}
                      onChange={this.personInput.bind(this, 'name')}
                      type='text' title='姓名' placeholder='购买人姓名' clear
                    ></AtInput>}
                    {custom_item_config.phone && <AtInput className='require' name='phone' value={payData.phone}
                      onChange={this.personInput.bind(this, 'phone')} type='text'
                      title='手机号码' maxLength={11} placeholder='购买人手机号'
                      clear
                    ></AtInput>}


                    {custom_item_config.idcard && <AtInput className='require' name='idcard' type='idcard'
                      value={payData.idcard} maxLength={18} title='身份证号'
                      placeholder='购买人身份证号'
                      onChange={this.personInput.bind(this, 'idcard')}
                    >
                      <AtIcon onClick={this.uplodeImg.bind(this, 0)} prefixClass='car' value='iconhexiao2' size='18'
                        color='#FCAA09'
                      />
                    </AtInput>}

                    {custom_item_config.address && <Block>
                      {TARO_ENV !== 'h5' ? <Picker mode='region' value={region} onChange={this.regionChange.bind(this)}>
                        <AtInput
                          className='require'
                          value={payData.province + payData.city + payData.region}
                          name='region' title='选择地区' placeholder='请选择地区'
                          customStyle='pointer-events: none;'
                        ></AtInput>
                      </Picker> : <Picker
                        mode='multiSelector' // 多列选择
                        onChange={this.onChange} // change事件
                        onColumnChange={this.onColumnChange} // 某列改变的事件
                        range={rangeData} //需要展示的数据
                        value={rangeKey} // 选择的下标
                      >
                        <View className='add-flex require'>
                          <View className='label'>所在地区</View>
                          <View className='addcheck'>
                            {regions[0] && (
                              <Text>
                                {regions[0] &&
                                <Text>{regions[0].indexOf(',') > -1 ? regions[0] : regions[0] + ','}</Text>}
                                {regions[1] &&
                                <Text>{regions[1].indexOf(',') > -1 ? regions[1] : regions[1] + ','}</Text>}
                                {regions[2] && <Text>{regions[2]}</Text>}
                              </Text>
                            )}
                            {!regions[0] && (
                              <Text style='color:#CCC'>选择省市区</Text>
                            )}
                            <AtIcon value='chevron-right' size='14' color='#888888' />
                          </View>
                        </View>
                      </Picker>}
                    </Block>
                    }
                    {custom_item_config.address && <AtInput className='require' name='address' type='text'
                      value={payData.address} title='详细地址' placeholder='详细地址'
                      onChange={this.personInput.bind(this, 'address')}
                    ></AtInput>}
                    {fieldCustom.map((item, index) =>
                      <Block key={index}>
                        <AtInput className={`${item.ckd ? 'require' : ''}`} name={item.name} type='text'
                          value={payData[item.name]} title={item.k}
                          onChange={this.personInput.bind(this, item.name)}
                        >
                        </AtInput>
                      </Block>)}
                    {custom_item_config.upload_file && <View className='uplode-box'>
                      <View className='uplode-title'><Text>*</Text>上传图片</View>
                      <View className='uplode-list'>
                        {payData.upload_file && payData.upload_file.length > 0 && payData.upload_file.map((v, i) =>
                          <View className='uplode-item' key={i}><View className='uplode-item-box'><View
                            className='uplode-close' onClick={this.delUplodeImg.bind(this, 0)}
                          ><AtIcon value='close'
                            size='12'
                            color='#999'
                          /></View><Image
                            src={v} mode='aspectFill'
                          ></Image></View></View>
                        )}
                        {upCount > payData.upload_file.length &&
                        <View className='uplode-item uplode-add' onClick={this.uplodeImg.bind(this, 1)}><AtIcon
                          value='add'
                          size='30'
                          color='#999'
                        /></View>}
                      </View>
                    </View>}
                    {custom_item_config.face && <View className='uplode-box'>
                      <View className='uplode-title'><Text>*</Text>上传人脸</View>
                      <View className='uplode-list'>
                        {payData.face &&
                        <View className='uplode-item'>
                          <View className='uplode-item-box'>
                            <View className='uplode-close' onClick={this.delUplodeImg.bind(this, 2)}>
                              <AtIcon value='close' size='12' color='#999' />
                            </View>
                            <Image src={payData.face} mode='aspectFill'></Image>
                          </View>
                        </View>}
                        {!payData.face &&
                        <View className='uplode-item uplode-add' onClick={this.uplodeImg.bind(this, 2)}><AtIcon
                          value='add' size='30' color='#999'
                        /></View>}
                      </View>
                    </View>}
                  </AtForm>
                </View>
              </Block>}
              <AtForm className='person'>
                {custom_item_config.mark &&
                <AtInput name='mark' type='text' value={payData.mark} title='备注' placeholder='特殊备注信息'
                  onChange={this.personInput.bind(this, 'mark')}
                />}
                {custom_item_config.comments &&
                <AtInput className='require' name='comments' type='text' value={payData.comments} title='留言'
                  placeholder='留言' onChange={this.personInput.bind(this, 'comments')}
                />}
              </AtForm>
              {openTraveler && goodDetail.goods && goodDetail.goods.is_custom_item > 0 && <View className='contact_box'>
                <View className='title'>
                  <View className='font_size_28'>联系人</View>
                  <View className='font_size_24'>请添加联系人用于接收出票信息</View>
                </View>
                <AtForm className='person'>
                  {custom_item_config.name &&
                  <AtInput name='linkman' value={payData.name} onChange={this.personInput.bind(this, 'name')}
                    type='text' title='姓名' placeholder='购买人姓名' clear
                  ></AtInput>}
                  {custom_item_config.phone &&
                  <AtInput name='phone' value={payData.phone} onChange={this.personInput.bind(this, 'phone')}
                    type='text'
                    title='手机号码' maxLength={11} placeholder='购买人手机号' clear
                  ></AtInput>}
                </AtForm>
              </View>}
            </View>
          </Skeleton>
          {feeInfo.is_group_leader_discount === '1' && !!isLeader && <View className='money group-box'>
            <View className='label'>活动优惠 <Text className='team-leader-discount' style={`color: ${dataColor.titleColor}`}>团长优惠</Text></View>
            <View className='val'
              style={`color: ${dataColor.priceColor}`}
            >-￥ {getFee.num == 0 ? 0 : feeInfo.totalFee}</View>
          </View>}
          {/*{this.getCanUseRedBag() && !fromGoodDetail && feeInfo.maxAmount > 0 && zero != 1 && feeInfo.platform_pay_type != 2 && !!feeInfo.is_can_use_hongbao &&*/}
          <View className='redbag' onClick={this.checkRedbag.bind(this)}>
            <View className='top'>
              <View className='title'>红包{redbag && feeInfo.hbAmount && <Text>{feeInfo.hbAmount}</Text>}</View>
              <View className='btn'>
                {redbag && feeInfo.hbAmount ? '-¥' + feeInfo.hbAmount : '选择红包'}
                <AtIcon value='chevron-right' size='16' color='#D0D0D0' />
              </View>
            </View>
            <View className='tips'>当前产品最大可用红包金额: ¥{feeInfo.maxAmount}</View>
          </View>{/*}*/}
          {!fromGoodDetail && (!!feeInfo.can_use_coupon && goodDetail.goods.is_self_meal !== 1) && !!feeInfo.is_can_use_coupon &&
          <View className='redbag' onClick={this.openCoupon.bind(this)}>
            <View className='top'>
              <View className='title coupon-title'>优惠券 <Text
                className='coupon-money-name'
              >{couponMoneyName}</Text></View>
              <View className='btn'>
                {couponMoney ? `-￥${couponMoney}` : '去用券'}<AtIcon value='chevron-right' size='16' color='#666' />
              </View>
            </View>
          </View>}
          {!fromGoodDetail && goodDetail && (goodDetail.integral.can && feeInfo.can) && zero != 1 && !!feeInfo.is_can_use_integral &&
          <View className='integral'>
            <AtSwitch checked={useIntegral} title={`${process.env.integralName}抵扣`} border={false}
              onChange={this.integralSwitch.bind(this)}
              color={`${process.env.mainColor}`}
            />
            {useIntegral && zero != 1 &&
            <View className='integral-box'>
              <View className='flex_center_between'>
                <View className='number'>
                  <View className='text'>使用 </View>
                  {(goodDetail && goodDetail.goods.exchange_type === 2) &&
                  <View>{goodDetail.goods.exchange_type === 2 ? goodDetail.integral.exchangeMaxIntegral : getFee.jf}</View>}
                  {(goodDetail && goodDetail.goods.exchange_type === 1) &&
                  <View>
                    <NumberInput canZero='true' val={getFee.jf}
                      step={1} min={0} disabled={alldisable}
                      showMaxToast={false}
                      max={goodDetail && feeInfo.maxJf && (feeInfo.maxJf <= goodDetail.integral.score ? feeInfo.maxJf : goodDetail.integral.score)}
                      thisChange={this.integralChangebtn.bind(this)}
                    />
                  </View>}
                  <View className='text'> {getGlobalData()}抵¥<Text className='price'>{feeInfo.integralDeduction}</Text>元</View>
                </View>
                <View className='jian_price'>-¥{feeInfo.integralDeduction}</View>
              </View>
              <View
                className='tips'
              >剩余：{goodDetail && goodDetail.integral.score}{getGlobalData()}，当前商品最大可用{ renderCanUseMaxJF() }{getGlobalData()}</View>
            </View>
            }
          </View>}
          {process.env.P_ENV === 'kd' &&
          <View className='integral'>
            <AtSwitch checked={openKD} title='蝌蚪币抵扣' border={false}
              onChange={this.integralSwitchKD.bind(this)}
              color={`${process.env.mainColor}`}
            />
            {openKD && <View className='integral-box'>
              <View className='flex_center_between'>
                <View className='number'>
                  <View className='text'>使用 </View>
                  <View>
                    <AtInputNumber type='digit'
                      step={1}
                      value={getFee.consume_fee.toString().match(/^\d+(?:\.\d{0,2})?/)}
                      min={0.00}
                      max={feeInfo.userCoinBalance}
                      onChange={this.integralChangebtnKD.bind(this)}
                    />
                  </View>
                  <View className='text'> 蝌蚪币抵¥<Text className='price'>{getFee.consume_fee}</Text>元</View>
                </View>
                <View className='jian_price'>-¥{getFee.consume_fee}</View>
              </View>
              <View
                className='tips'
              >当前可用：{feeInfo.userCoinBalance}蝌蚪币</View>
            </View>}
          </View>
          }

          <View className='agreement'>
            <Checkbox className='check-box-width' value='true' onClick={this.agree.bind(this, agree)}
              checked={agree}
            />
            {process.env.P_ENV !== 'kontai' ? <Block>
                {!!platformSet.platform_terms_of_service_new ? <Block>
                  {process.env.TARO_ENV === "weapp" &&
                  <parser selectable html={platformSet.platform_terms_of_service_new || ''} />}
                  {process.env.TARO_ENV === "tt" &&
                  <rich-text preview selectable nodes={getContent(platformSet.platform_terms_of_service_new)} />}
                  {process.env.TARO_ENV === "h5" &&
                  <View dangerouslySetInnerHTML={{__html: platformSet.platform_terms_of_service_new}} />}
                </Block> : <Block>
                  <Text>我已经查看并同意"产品抢购须知"和</Text><Navigator
                    url='/other/agreement/service'
                    className='clause'
                  >"{platformSet.platform_terms_of_service}"</Navigator>
                </Block>}
              </Block>
              :
              <Block>
                {(goodDetail.goods.category === 3 || goodDetail.goods.category === 2) ?
                  <Block>
                    {this.siteHash === '950f5513-8b0f-4909-9cc1-75abd92d2737' ? <Block>
                      {goodDetail.goods.category === 3 ?
                        <View>我已阅读并知晓出行休养行程安排、休养价格、休养服务标准及温馨提醒中的相关内容、预定须知、<Text onClick={() => {
                          Taro.navigateTo({url: '/other/agreement/service'})
                        }} className='clause'
                          style='display: initial;'
                        >《职工疗休养服务合同》</Text>中的相关内容，并已告知随行人员，视同你单位告知。</View> :
                        <View>我已阅读并知晓出行行程安排、行程价格、服务标准以及温馨提醒中的相关内容、<Text onClick={() => {
                          Taro.navigateTo({url: '/other/agreement/lineService'})
                        }} className='clause'
                        >《团队境内旅游合同》</Text>中的相关内容，并已告知随行人员，视同你单位告知。</View>
                      }
                    </Block> : <Block>
                      <View style='display: flex;'>
                        <View>我已阅读并知晓出行行程安排、行程价格、服务标准及温馨提醒中的相关内容、<Navigator url='/other/agreement/lineService'
                          className='clause'
                        >《团队境内旅游合同》</Navigator> 中的相关内容，并已告知随行人员，视同你单位告知。</View>
                      </View>
                    </Block>}
                  </Block>
                  :
                  <Block>
                    <Text>我已经查看并同意"产品抢购须知"和</Text>
                    <Navigator url='/other/agreement/service'
                      className='clause'
                    >"{platformSet.platform_terms_of_service}"</Navigator>
                  </Block>}
              </Block>
            }
          </View>
          {feeInfo.warn_info &&
          <View className='group-tip-warning'><View className='group-warn_info'><AtIcon size='12px' color='red'
            value='icon icon-gantanhao-sanjiaokuang'
          /><Text
            className='text-warn_info'
          >{feeInfo.warn_info}</Text></View></View>}
          <View style='height: 100px;' />
          <View className={`footer-btn ${isiPhonex ? 'is-iphone-x' : ''}`}>
            <View className='right'>
              {isDaypartingAppointment && (process.env.P_ENV == 'vc' || process.env.P_ENV == 'kunxin') ?
                <View className='price'></View> : <View className='price'>
                  <View className='price_text'>合计：</View>
                  {zero == 1 && !fromGoodDetail ?
                    <View className='text' style={`color: ${dataColor.priceColor}`}>￥0</View> :
                    <View style={`color: ${dataColor.priceColor}`}
                      className='text'
                    >¥ {fromGoodDetail ? fromGoodDetail.trans_price : getFee.num == 0 ? 0 : feeInfo.totalFee}</View>}
                  {(feeInfo && feeInfo.discounts_money > 0 && !fromGoodDetail) ?
                    <View onClick={this.lookDetail.bind(this)} className='detail'>明细
                      {detailShow && <AtIcon value='chevron-down' size='14' color='#999' />}
                      {!detailShow && <AtIcon value='chevron-up' size='14' color='#999' />}
                    </View> : <View style='width: 10px' />}
                </View>}
              {zero == 1 && !fromGoodDetail ? <Button disabled={submiting} loading={submiting} className='btn'
                onClick={this.payFn.bind(this, 1)}
              >{isDaypartingAppointment && (process.env.P_ENV == 'vc' || process.env.P_ENV == 'kunxin') ? '立即预订' : '免费领取'}</Button> :
                <Block>
                  {userOk == 1 && <Button disabled={submiting || ticketSubMiting} loading={submiting} className='btn'
                    onClick={this.submitCheck.bind(this, feeInfo)}
                  >{isDaypartingAppointment && (process.env.P_ENV == 'vc' || process.env.P_ENV == 'kunxin') ? '立即预订' : onlyTicketPay === '1' ? '立即兑换' : '立即支付'}</Button>}
                  {userOk == 2 &&
                  <Button className='btn' openType='getPhoneNumber' onGetPhoneNumber={this.getPhoneNumber.bind(this)}
                    onError={(err) => {
                            console.log(err)
                          }}
                  >{isDaypartingAppointment && (process.env.P_ENV == 'vc' || process.env.P_ENV == 'kunxin') ? '立即预订' : onlyTicketPay === '1' ? '立即兑换' : '立即支付'}</Button>}
                </Block>
              }
            </View>
          </View>
          {showCalendar && <Calendar env={_env} fristShow={fristShow} onClose={() => {
            this.setState({showCalendar: false})
          }} data={calendarInfo} mode='callback' type={goodDetail.goods.category === 2 ? 'range' : 'single'}
            day_end={booking_day_end} time_end={booking_time_end}
            category={goodDetail.goods.category}
            single={buyDate.start}
            onConfirm={this.calendarSelect.bind(this)}
          ></Calendar>}
          <AtModal onClose={this.handleClose.bind(this)} isOpened={userBalance && platformSet.payVersion === 1}>
            <AtModalContent>
              <View className='modal-box'>
                <View className='modal-title'>选择支付方式</View>
                {/* {process.env.P_ENV === 'kd' &&
                <Block>
                  {feeInfo.userCoinBalance >= feeInfo.totalFee ?
                    <View className="modal-item" onClick={this.payFn.bind(this, 4)}><Image
                      src={RESOURCE_URL + "/upload/images/20220130/1643551597986_748.png"}/>蝌蚪币支付（剩余￥{feeInfo.userCoinBalance}）<View
                      className="right"><AtIcon
                      value='chevron-right' size='15' color='#c9c9c9'/></View></View>
                  :
                    <View className="modal-item disabled"><Image
                      src={RESOURCE_URL + "/upload/images/20220130/1643551597986_748.png"}/>蝌蚪币支付（剩余￥{feeInfo.userCoinBalance}）<View
                      className="right"><AtIcon
                      value='chevron-right' size='15' color='#c9c9c9'/></View></View>}
                </Block>
                }*/}
                <View className='modal-item' onClick={this.payFn.bind(this, 0)}><Image
                  src={RESOURCE_URL + "/resources/weapp/images/wxico.png"}
                />微信支付 <View className='right'><AtIcon
                  value='chevron-right' size='15' color='#c9c9c9'
                /></View></View>

                <View className='close-modal' onClick={this.sureCheckClose.bind(this)}><AtIcon value='close' size='15'
                  color='#333'
                /></View>
                {feeInfo.userBalance >= feeInfo.totalFee && process.env.P_ENV !== 'lx' ?
                  <View className='modal-item' onClick={this.payFn.bind(this, 1)}><Image
                    src={RESOURCE_URL + "/resources/weapp/images/yeico.png"}
                  />余额（剩余￥{feeInfo.userBalance}） <View
                    className='right'
                  ><AtIcon value='chevron-right' size='15' color='#c9c9c9' /></View></View>
                  :
                  <View className='modal-item disabled'><Image
                    src={RESOURCE_URL + "/resources/weapp/images/yeico.png"}
                  /><View className='czbox'><View
                    className='cztext'
                  >余额（剩余￥{feeInfo.userBalance}）</View><View className='cztext'>余额不足</View></View>
                    {_env != 'pc' && <View className='right' onClick={this.chongzhi.bind(this)}>去充值</View>}
                  </View>
                }
                {!!feeInfo.isOpenCredit && !activityId && getFee.consume_fee <= 0 &&
                <Block>
                  {(Number(feeInfo.creditAmount) || 0) >= Number(feeInfo.totalFee) ?
                    <View className='modal-item' onClick={this.payFn.bind(this, 3)}><Image
                      src={RESOURCE_URL + "/resources/weapp/images/xinicon.png"}
                    />授信支付<View
                      className='right'
                    ><AtIcon
                      value='chevron-right' size='15' color='#c9c9c9'
                    /></View></View>
                    :
                    <View className='modal-item disabled'><Image
                      src={RESOURCE_URL + "/resources/weapp/images/xinicon.png"}
                    />授信支付<View
                      className='right'
                    ><AtIcon
                      value='chevron-right' size='15' color='#c9c9c9'
                    /></View></View>
                  }
                </Block>
                }
                {goodDetail && !!goodDetail.goods.can_use_conversion_code && !activityId &&
                <View className='modal-item' onClick={this.toggleWelfare.bind(this)}><Image
                  src={RESOURCE_URL + "/resources/weapp/images/flico.png"}
                />兑换码 <View className='right'><AtIcon
                  value='chevron-right' size='15' color='#c9c9c9'
                /></View></View>}
              </View>
            </AtModalContent>
          </AtModal>
          {welfare && <View className='welfare'>
            <View className='welfare_bj' onClick={this.toggleWelfare.bind(this)}></View>
            <View className='welfare_box'>
              <View className='offbtn' onClick={this.toggleWelfare.bind(this)}><AtIcon value='close' size='20'
                color='#fff'
              /></View>
              <Image className='welfare_header' mode='widthFix'
                src='https://resource.ivcheng.com/resources/images/fl_bj.png'
              ></Image>
              <View className='welfare_list_box'>
                <View className='welfare_list'>
                  {flAry.length > 0 && flAry.map((item, i) =>
                    <View className='welfare_item' key={i}>
                      <Input value={item} type='text' placeholder='请输入兑换码' onInput={this.flInput.bind(this, i)}></Input>
                      {flAryIndex === i && <View className='welfare_tipe'>{flAryMsg}</View>}
                    </View>
                  )}
                </View>
                <View className='welfare_sure' onClick={this.payFn.bind(this, 2)}>确定兑换</View>
              </View>
            </View>
          </View>}
        </Block>}
        <AtFloatLayout className='layout_idcard' isOpened={floatLayoutIdcard} scrollY={false}>
          <View className='flex_center_between operating'>
            <View onClick={() => this.setState({floatLayoutIdcard: false})}>取消</View>
            <View onClick={() => this.setState({floatLayoutIdcard: false})}>确定</View>
          </View>
          <View onClick={this.newAddJump.bind(this)} className='flex_center_center add-box'>
            <AtIcon value='add-circle' size='22' color='#EDAF2E' />
            <Text>新增</Text>
          </View>
          <ScrollView scrollY className='layout_idcard_item_box' scrollIntoView={`${bottomView}`}>
            {contactData && contactData.length > 0 && contactData[layoutIndex].map((list, idx) =>
              <View
                id={`bottomView${idx}`}
                onClick={this.selectContact.bind(this, layoutIndex, idx, goodDetail.goods.is_custom_item == 0 ? 1 : getFee.num)}
                key={idx} className='layout_idcard_item'
              >
                <View
                  onClick={this.edit.bind(this, layoutIndex, 0, goodDetail.goods.id, goodDetail.goods.custom_item_config, list.value[0].phone, list.value[0].name)}
                >
                  <AtIcon prefixClass='car' value='iconbianji' size='18' color='#999' /></View>
                <View className={`confirm-info ${TARO_ENV + 'info'}`}>
                  <View className='view1'> {list.value[0].name}</View>
                  {custom_item_config.idcard && <View className='view2'>身份证 {list.value[0].idcard}</View>}
                  {list.value[0].phone && <View className='view3'>手机号 {list.value[0].phone}</View>}
                </View>
                <View>
                  {list.value[0].checked && <View className='idcard_checked'>
                    <Image mode='widthFix' style='width: 32px;heigth:32px'
                      src='https://resource.ivcheng.com/resources/weapp/images/xuan.png'
                    />
                  </View>}
                  {!list.value[0].checked && <View className='idcard_checked_no'>

                  </View>}
                </View>
              </View>)}
          </ScrollView>
        </AtFloatLayout>
        {pcQrcodeShow && <View className='curtainRoot'>
          <View className='pc-root'>
            <Image className='pcqrcode' src={pcqrcode} mode='widthFix' />
            <View className='pc-tips'>请用微信扫码支付</View>
            <View onClick={() => {
              this.setState({pcQrcodeShow: false, submiting: false})
            }} className='gzh-close'
            >
              <AtIcon value='close' color='#000' />
            </View>
          </View>
        </View>}
        <AtFloatLayout isOpened={floatLayout} title='购买须知' scrollY onClose={() => {
          this.setState({floatLayout: false})
        }}
        >
          {(process.env.TARO_ENV === "weapp" || process.env.TARO_ENV === "tt") ?
            <Block>
              <View className='float-layout' id='xuzhi'>
                {process.env.TARO_ENV === "weapp" && <parser html={notice || ''} />}
                {process.env.TARO_ENV === "tt" && <rich-text preview selectable nodes={getContent(notice)} />}
              </View>
            </Block>
            :
            <Block>
              {!!goodDetail && !!goodDetail.goods.notice &&
              <View dangerouslySetInnerHTML={{__html: goodDetail.goods.notice}} className='float-layout' id='xuzhi'>
              </View>}
            </Block>}

        </AtFloatLayout>
        {!!feeInfo.can_use_coupon && feeInfo.coupon_list.length > 0 &&
        <Block><AtFloatLayout isOpened={offOpenCoupon} title='店铺优惠' onClose={() => {
          this.setState({offOpenCoupon: false})
        }} scrollY
        >
          {feeInfo.coupon_list.map((val, i) =>
            <View className='group-item' key={i} onClick={this.checkMeal.bind(this, i)}>
              <View className='group-nametop'>{val.name}</View>
              <View className='group-product'>
                <View className='group-name'>{val.amount_limit_str}<Text>-￥{val.coupon_discounts_money}</Text></View>
                <View className='group-check'>{(val.id == feeInfo.couponIsuseId && !notUse) ?
                  <Image src={RESOURCE_URL + "/resources/weapp/images/xuan.png"} /> :
                  <View className='only' />}</View>
              </View>
            </View>
          )}
          <View className='group-item'>
            <View className='group-product' onClick={this.checkMeal.bind(this, -1)}>
              <View>不使用优惠券</View>
              <View className='group-check'>{notUse ? <Image src={RESOURCE_URL + "/resources/weapp/images/xuan.png"} /> :
                <View className='only' />}</View>
            </View>
          </View>
        </AtFloatLayout>
        </Block>}
        {paySuccessShow && <View className='curtainRoot'>
          <View className='pc-root'>
            <Icon size='60' type='success' />
            <View style='color: #333; font-size: 18px; margin-top: 20px;'>支付成功</View>
          </View>
        </View>}
        {detailShow &&
        <View onClick={() => {
          this.setState({detailShow: false})
        }} className='price_detail_box'
        >
          <View className='price_detail'>
            <View className='title'>费用明细</View>
            <View className='charge-details-money-wrapper-box'>
              {!!feeInfo.goodsPrePrice && <View className='charge-details-money-wrapper'>
                <View>商品金额</View>
                <View
                  className='charge-details-money-wrapper-price font-family-price'
                >￥{feeInfo.goodsPrePrice.toFixed(2)}</View>
              </View>}
              {!!feeInfo.hbAmount && <View className='charge-details-money-wrapper'>
                <View>红包</View>
                <View
                  className='charge-details-money-wrapper-price font-family-price'
                >￥{feeInfo.hbAmount.toFixed(2)}</View>
              </View>}
              {!!feeInfo.integralDeduction && <View className='charge-details-money-wrapper'>
                <View>积分</View>
                <View
                  className='charge-details-money-wrapper-price font-family-price'
                >￥{feeInfo.integralDeduction.toFixed(2)}</View>
              </View>}
              {!!feeInfo.coupon_discount_money && <View className='charge-details-money-wrapper'>
                <View>优惠券</View>
                <View
                  className='charge-details-money-wrapper-price font-family-price'
                >￥{feeInfo.coupon_discount_money.toFixed(2)}</View>
              </View>}
              {!!feeInfo.goods_discount_code_money && <View className='charge-details-money-wrapper'>
                <View>推广优惠</View>
                <View
                  className='charge-details-money-wrapper-price font-family-price'
                >￥{feeInfo.goods_discount_code_money.toFixed(2)}</View>
              </View>}
            </View>
          </View>
        </View>}
      </View>
    );
  }
}

export default Confirm as ComponentClass<PageOwnProps, PageState>
